Does this need explicit synchronization?
I have two threads, and I want to make sure I am doing the synchronization correctly on the LinkedBlockingQueue.. Is this correct? Or is the explicit synchronization on (messageToCommsQueue) not necessary?
Declaration:
private LinkedBlockingQueue<BaseMessage> messagesToCommsQueue;
Method one:
private void startOperationModeStatusMessageExecutor() {
ScheduledExecutorService operationModeStatusExecutor = Executors.newSingleThreadScheduledExecutor();
operationModeStatusExecutor.scheduleAtFixedRate((new Runnable() {
@Override
public void run() {
ModeStatusMessage commsOperateMsg;
commsOperateMsg = MessageFactory.getModeStatusMessage(status.ordinal());
synchronized (messagesToCommsQueue) {
messagesToCommsQueue.add(commsOperateMsg);
}
}
}), 0, 10, TimeUnit.SECONDS);
}
Method Two:
Executor commsSenderExecutor = Executors.newSingleThreadExecutor();
commsSenderExecutor.execute(new Runnable() {
@Override
public void run() {
while (getStatus().equals(ModeStatus.INITIATE) || getStatus().equals(ModeStatus.OPERATE)) {
BaseMessage m = null;
try {
synchronized (messagesToCommsQueue) {
m = messagesToCommsQueue.take();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
开发者_如何学JAVA e.printStackTrace();
}
}
}
});
Yes, it's not necessary. JavaDoc says that:
BlockingQueue implementations are thread-safe.
精彩评论