views:

55

answers:

1

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() {
            MT02OperationModeStatusMessage commsOperateMsg;
                commsOperateMsg = MessageFactory.getMT1102OperationModeStatusMessage(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(OperationModeStatus.INITIATE) || getStatus().equals(OperationModeStatus.OPERATE)) {
                BaseMessage m = null;
                try {
                    synchronized (messagesToCommsQueue) {
                        m = messagesToCommsQueue.take();
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }



            }
        }

    });
+3  A: 

Yes, it's not necessary. JavaDoc says that:

BlockingQueue implementations are thread-safe.

splix