【发布时间】:2016-05-15 21:03:51
【问题描述】:
我有一个实用程序类,它有一个静态方法来修改输入数组列表的值。此静态方法由调用者调用。调用者用于处理 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;
}
鉴于上述定义,通过不同步静态方法,它是否仍然能够正确处理并发方法调用。我的理解是我必须同步此方法以进行并发但想确认。 我知道每个线程都有自己的堆栈,但是对于静态方法,它对所有线程都是通用的 - 所以在这种情况下,如果我们不同步它不会导致问题吗? 感谢建议和任何更正。
谢谢
【问题讨论】:
-
“预设搜索条件”是否曾被另一个线程更改过? “之后做某事”是否对线程之间共享的任何数据做任何事情?
-
getClonedCriteria是返回同步副本还是仅返回参考副本? -
预设标准没有改变。公共同步静态 ArrayList
cloneSearchCriteria(ArrayList criteria) { if (criteria == null) return null; ArrayList criteriaClone = new ArrayList (); for (Properties sc : 标准) { 属性克隆 = 新属性 ();枚举propertyNames = sc.propertyNames(); while (propertyNames.hasMoreElements()) { String key = (String) propertyNames.nextElement(); clone.put(key, (String) sc.get(key)); } 标准Clone.add(克隆); } 返回条件克隆; } -
对不起。无法格式化代码..但是 cloneSearchCriteria() (我已为这篇文章重命名为 getClonedCriteria() 是同步的
-
您仍然没有显示原始标准是如何初始化的。
cloneSearchCriteria()方法只要处理好原始条件就不需要同步了。
标签: java multithreading concurrency thread-safety