In my use case, I want to return a user object from the lambda function as in the code below. Before posting my question, I try many similar questions like this and this but no theme solves my problem, here is my code:
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class AppDatabase {
private static final int NUMBER_OF_THREADS = 4;
public static final ExecutorService databaseWriteExecutor =
Executors.newFixedThreadPool(NUMBER_OF_THREADS);
}
public class MyClass {
private User mUser;
public User findUser(){
AppDatabase.databaseWriteExecutor.execute(() -> {
mUser = work();
});
return mUser;
}
public User work(){
//simulate get user from database
User user = new User();
user.setName("Toto");
return user;
}
}
public class Main {
public static void main(String[] args) {
MyClass myClass = new MyClass();
User user;
user = myClass.findUser();
System.out.println(user.getName()); //this line: Exception in thread "main" java.lang.NullPointerException
}
}
When I run this code, I get "Exception in thread" main "java.lang.NullPointerException". My question is how do I get the User object built by the work () function, but this function should run in a background thread like in code.
findUser
returns right away, and it returns null
because mUser
hasn't been set yet. You need to either wait for it to be set, or return a Future<User>
that the caller can wait on.