samedi 30 avril 2016

Eventually load member variable value in a non blocking thread safe manner

I have a class that has a getter method (among others):

public class Employee {  

  public EmployeeAccount getAccount() {  
     return this.empAccount;  
  }  
}  

The problem is that the empAccount is initialized by an async call which might return null but eventually would return the actual account.
The reason is that the async call method depends on many things and sometimes might return null as it is not ready to give the account yet. Please note that I have no control over this API.
So I was thinking of doing something like:

public class Employee {  
   public EmployeeAccount getAccount() {  
      if(this.empAccount != null) {   
         retrieveAccount(); 
      }
       return this.empAccount; 
   }
   private void retrieveAccount() {  
      Thread t = new Thread(new Runnable() {  
          @Override   
          public void run() {  
             this.empAccount = getAccountFromRemoteSystem(); // <--- this is a blocking call   
          }  
      };  
     t.start();  
}  

The reason I was aiming towards this is because getAccount() is expected to be non-blocking as it is called from a UI thread.
How can I design/structure my code so that it is thread safe? Are there better constructs I can use or some other design pattern?

Aucun commentaire:

Enregistrer un commentaire