Do I need synchronise on objects which guarantee happen-before?
I have a collection which guaranteed to be visible across threads. However that doesn't guarantee visibility of states of items which are stored in this collection(eg. if I have collection of StringBuilder(mutable, not thread safe) then I have to synchronize on each item in collection during write/read, right?). So, what happens when I have collection of objects which are used for guaranteeing happen-before by themselves(eg. countdownlatch). Do I need to synchronize on each item somehow when calling await/countDown? Code below roughly illustrate this dilemma:
public class SyncQuestion {
final List<CountDownLatch> lathces = new ArrayList<CountDownLatch>();
SyncQuestion() {
lathces.add(new CountDownLatch(1));
}
public static void main(String[] args) throws InterruptedException {
final SyncQuestion sync = new SyncQuestion();
final Thread sleepingThread = new Thread() {
public void run() {
for (CountDownLatch latch : sync.lathces) {
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
};
final Thread wakingThread = new Thread() {
public void run() {
for (CountDownLatch latch : sync.lathces) {
latch.countDown();
}
};
};
sleepingThread.start();
wakingThread.start();
sleepin开发者_如何学GogThread.join();
wakingThread.join();
}
}
Please correct me in my assumptions, if they are wrong.
A CountDownLatch
is basically a wrapper on AbstractQueuedSynchronizer
whose state is a volatile int that is mutated via Unsafe.compareAndSwapInt
(which is an atomic operation).
Therefore in this specific case, as Cameron Skinner said, there is no need to synchronize because it enforces that happens-before for you.
I don't believe you need to manually synchronize in this case because the latches are internally thread-safe.
精彩评论