java - What is the best way to ensure concurrent object calls without locking -


i have following objects:

// class immutable, acts container several properties. public class mydataaddops{     private final boolean isactive;     private final map<string,object> additionalprops;      public mydataaddops(boolean isactive, map<string,object> additionalprops){        this.isactive = isactive;        this.additionalprops = additionalprops;     }     public boolean isactive(){return isactive;}    public map<string,object> getadditionalprops(){ return additionalprops;} }  // class acts "spring" bean calls load on construction, //  , scheduler bean calls load per cron expression (once minute example)  public class mydataaddopsservice{    private mydataaddops data;     // method executed periodically outside    // via spring quartz example    // quartz not re-entrant      public void load(){       // opens defined file , returns content string        string filedata = getfilecontent();        boolean isactive = getisactive(filedata);       map<string, object> props = getprops(filedata);       data = new mydataaddops(isactive, props);    }    // method executed many workers threads inside application   public boolean isactive(){      return data.isactive();   }    public final map<string, object> getprops(){       return data.getadditionalprops();   }   } 

this approach has race condition 1 thread executes isactive() , load(). although operates on reference , object state not changed.

what best solution support such concurrency? avoid syncronized on methods, , read-write lock.

maybe atomicreference or volatile? or maybe better return reference data without proxy methods? no need locking @ all, , usage logic outside service?

 public class mydataaddopsservice{    private mydataaddops data;    public void load(){      ....      data = new mydataaddops(isactive, props);    }   public mydataaddops getdata(){     return data;   }  } 

your code has yet grow towards having race condition; contains more severe, data race. publishing reference across threads without inducing happens before relationship between write , future reads means reader can see data object in partially initialized, inconsistent state. proposal of solution not that.

once make data field volatile, then have race condition between 1 thread first reading data reference, thread updating data reference, first thread reading isactive old data. may benign case logic.


Comments