java - Instance-controlled classes and multithreading -


in effective java chapter 2, item 1 bloch suggests consider static factory methods instead of constructors initalize object. on of benefits mentions pattern allows classes return same object repeated invocations:

the ability of static factory methods return same object repeated invocations allows classes maintain strict control on instances exist @ time. classes said instance-controlled. there several reasons write instance-controlled classes. instance control allows class guarantee singleton (item 3) or noninstantiable (item 4). also, allows immutable class (item 15) make guarantee no 2 equal instances exist: a.equals(b) if , if a==b.

how pattern work in multi threaded environment? example, have immutable class should instance-controlled because 1 entity given id can exist @ time:

public class entity {      private final uuid entityid;      private static final map<uuid, entity> entities = new hashmap<uuid, entity>();      private entity(uuid entityid) {         this.entityid = entityid;     }      public static entity newinstance(uuid entityid) {         entity entity = entities.get(entityid);         if (entity == null) {             entity = new entity(entityid);             entities.put(entityid, entity);         }         return entity;     }  } 

what happen if call newinstance() separated threads? how can make class thread-safe?

make newinstance synchronized is

public static synchronized entity newinstance(uuid entityid){      ... } 

so 1 thread enters new instance method, no other thread can invoke method unless first thread finishes. happens first thread gets lock entire class. time first thread holds lock class, no other thread can enter synchronized static method class.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -