我有一个工具类有一个静态方法来修改输入数组列表的值。这个静态方法由调用者调用。调用者用于处理Web服务请求。对于每个请求(每个线程),调用者创建一个新的ArrayList并调用静态方法。这是静态方法线程安全或需要同步
public class Caller{
public void callingMethod(){
//Get Cloned criteria clones a preset search criteria that has place holders for values and returns a new ArrayList of the original criteria. Not included code for the clone
ArrayList<Properties> clonedCriteria = getClonedCriteria();
CriteriaUpdater.update(clonedCriteria , "key1", "old_value1", "key1_new_value");
CriteriaUpdater.update(clonedCriteria , "key2", "old_value2", "key2_new_value");
//do something after the this call with the modified criteria arraylist
}
}
public class CriteriaUpdater
{
//updates the criteria, in the form of array of property objects, by replacing the token with the new value passed in
public static void update(ArrayList<Properties> criteria, String key, String token, String newValue)
{
for (Properties sc: criteria)
{
String oldValue = sc.getProperty(key);
if ((oldValue != null) && (oldValue.equals(token)))
sc.setProperty(key, newValue);
}
}
}
这就是标准如何被克隆:
public synchronized static ArrayList<Properties> cloneSearchCriteria(ArrayList<Properties> criteria) {
if (criteria == null) return null;
ArrayList<Properties> criteriaClone = new ArrayList<Properties>();
for (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;
}
鉴于上述定义,通过不同步的静态方法,将它仍然能够正确处理并发方法调用。我的理解是我必须同步这种并发的方法,但想确认。 我知道每个线程都有自己的堆栈,但是对于静态方法来说,它对于所有线程都很常见 - 所以在这种情况下,如果我们不同步,它不会导致问题? 欣赏建议和任何更正。
谢谢
“预设搜索条件”是否被另一个线程更改过?在“线程之间共享任何数据做任何事情之后都会做些什么? – rgettman
'getClonedCriteria'返回一个同步副本,或只是一个参考副本? – Tersosauros
预设标准不会更改。 公共同步静态的ArrayList cloneSearchCriteria(ArrayList的条件){ \t \t如果(标准== NULL) \t \t \t返回NULL; \t \t ArrayList criteriaClone = new ArrayList (); (Properties sc:criteria) \t \t(012) \t \t \t Enumeration propertyNames = sc.propertyNames(); \t \t \t而(propertyNames.hasMoreElements()){ \t \t \t \t String键=(字符串)propertyNames.nextElement(); \t \t \t \t clone.put(key,(String)sc.get(key)); \t \t \t} \t \t \t criteriaClone.add(克隆); \t \t} \t \t return criteriaClone; \t} –
sbelvadi