我定义了一个Element类:
class Element<T> {
T value;
Element<T> next;
Element(T value) {
this.value = value;
}
}
同时还定义了一个基于Element的List类。它是一个典型的列表,就像在任何数据结构书籍中一样,具有添加头部、删除等操作。
public class List<T> implements Iterable<T> {
private Element<T> head;
private Element<T> tail;
private long size;
public List() {
this.head = null;
this.tail = null;
this.size = 0;
}
public void insertHead (T node) {
Element<T> e = new Element<T>(node);
if (size == 0) {
head = e;
tail = e;
} else {
e.next = head;
head = e;
}
size++;
}
//Other method code omitted
}
如何使这个List类线程安全?
在所有方法上放置synchronized?似乎不起作用。两个线程可能同时在不同的方法上工作,导致冲突。
如果我使用数组来保存类中的所有元素,那么我可以在数组上使用volatile,以确保只有一个线程正在处理内部元素。但目前所有元素都通过每个元素的下一个指针链接。我无法使用volatile。
在head、tail和size上使用volatile?如果两个线程运行不同的方法并相互持有资源等待,则可能会导致死锁。
有什么建议吗?
synchronized
表现良好。更细粒度的锁定是减少争用的一种方式。 - Stephen C