这个article解释了“双重检查锁定”,其思想是减少锁争用。正如这篇文章所解释的那样,它不起作用。参见表中的代码示例“(仍然)损坏的多线程版本”双重检查锁定“惯用法”。
现在我想我找到了一个可以工作的变体。问题是这是否正确。假设我们有一个消费者和一个生产者,它们通过共享队列交换数据:
class Producer {
private Queue queue = ...;
private AtomicInteger updateCount;
public void add(Data data) {
synchronized(updateCount) {
queue.add(task);
updateCount.incrementAndGet();
}
}
}
class Consumer {
private AtomicInteger updateCount = new AtomicInteger(0);
private int updateCountSnapshot = updateCount.get();
public void run() {
while(true) {
// do something
if(updateCountSnapshot != updateCount.get()) {
// synchronizing on the same updateCount
// instance the Producer has
synchronized(updateCount) {
Data data = queue.poll()
// mess with data
updateCountSnapshot = updateCount.get();
}
}
}
}
}现在的问题是,你是否认为这种方法有效。我要求确认,因为如果不这样做,很多东西都会坏掉……这个想法是为了减少锁争用,当同时updateCount发生变化时,只进入消费者中的同步块。
发布于 2014-11-19 23:35:25
我怀疑你更多的是在找一个Code Review。
您应该考虑以下几点:
,
updateCount。这里有一个简单的生产者/消费者对用于演示。
public class TwoThreads {
public static void main(String args[]) throws InterruptedException {
System.out.println("TwoThreads:Test");
new TwoThreads().test();
}
// The end of the list.
private static final Integer End = -1;
static class Producer implements Runnable {
final Queue<Integer> queue;
public Producer(Queue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (int i = 0; i < 1000; i++) {
queue.add(i);
Thread.sleep(1);
}
// Finish the queue.
queue.add(End);
} catch (InterruptedException ex) {
// Just exit.
}
}
}
static class Consumer implements Runnable {
final Queue<Integer> queue;
public Consumer(Queue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
boolean ended = false;
while (!ended) {
Integer i = queue.poll();
if (i != null) {
ended = i == End;
System.out.println(i);
}
}
}
}
public void test() throws InterruptedException {
Queue<Integer> queue = new LinkedBlockingQueue<>();
Thread pt = new Thread(new Producer(queue));
Thread ct = new Thread(new Consumer(queue));
// Start it all going.
pt.start();
ct.start();
// Wait for it to finish.
pt.join();
ct.join();
}
}https://stackoverflow.com/questions/27005481
复制相似问题