【发布时间】:2015-07-27 06:01:02
【问题描述】:
在为 Collections.synchronizedList 编写 putIfAbsent 方法时,需要在访问列表期间提供显式锁定。
下面的代码 sn -p 更详细地解释它:
class ListHelper <E> {
List<Employee> employeeList = new ArrayList<Employee>();
employeeList.add(new Employee());
//.. add more eomployees like this to the list
public List<E> list = Collections.synchronizedList(employeeList);
public boolean putIfAbsent(Employee x) {
boolean absent = !employeeList.contains(x);
if (absent)
employeeList.add(x);
return absent;
}
}
请解释为什么当我们有 Collections.synchronizedList 时在 put-if-absent 方法中需要 synchronized(employeeList),它在 ArrayList 对象上有一个锁。
谢谢
【问题讨论】:
-
list是一个字段吗?list的初始化表达式中的employeeList是什么? -
employeeList 是具有员工对象值的简单数组列表
-
你能发布一个完整的例子吗?我觉得缺少一些上下文。
标签: java concurrency synchronized