java - Is this static method thread safe or is synchronization needed -
i have utility class has 1 static method modify values of input array list. static method invoked caller. caller used process web service requests. each request(per thread), caller creates new arraylist , invokes static method.
public class caller{ public void callingmethod(){ //get cloned criteria clones preset search criteria has place holders values , returns new arraylist of original criteria. not included code clone arraylist<properties> clonedcriteria = getclonedcriteria(); criteriaupdater.update(clonedcriteria , "key1", "old_value1", "key1_new_value"); criteriaupdater.update(clonedcriteria , "key2", "old_value2", "key2_new_value"); //do after call modified criteria arraylist } } public class criteriaupdater { //updates criteria, in form of array of property objects, replacing token new value passed in public static void update(arraylist<properties> criteria, string key, string token, string newvalue) { (properties sc: criteria) { string oldvalue = sc.getproperty(key); if ((oldvalue != null) && (oldvalue.equals(token))) sc.setproperty(key, newvalue); } } }
this how criteria cloned:
public synchronized static arraylist<properties> clonesearchcriteria(arraylist<properties> criteria) { if (criteria == null) return null; arraylist<properties> criteriaclone = new arraylist<properties>(); (properties sc : criteria) { properties clone = new properties(); enumeration propertynames = sc.propertynames(); while (propertynames.hasmoreelements()) { string key = (string) propertynames.nextelement(); clone.put(key, (string) sc.get(key)); } criteriaclone.add(clone); } return criteriaclone; }
given above definitions, not synchronizing static method, still able correctly process concurrent method calls. understanding have synchronize method concurrency wanted confirm. understand each thread have own stack, static method common threads - in case if don't synchronize not cause problem? appreciate suggestions , corrections.
thanks
it depends on getclonedcriteria()
method. that's method accessing shared state.
you creating "deep copy" of criteria, every clone independent original , each other.
but there's more subtle problem, whatever initialization performed on prototype criteria must happen-before thread reads criteria clone it. otherwise, cloning thread may read uninitialized version of data structure.
one way achieve initialize prototype criteria in static initializer , assign class member variable. initialize criteria and then assign volatile
variable. or, initialize , assign prototype (in either order) ordinary class or instance member variable inside synchronized
block (or using lock
), , read variable block synchronized on same lock.
Comments
Post a Comment