gcasar
gcasar

Reputation: 759

Do ArrayBlockingQueue wrapper methods need to be synchronized?

I have two threads, one that dispatches messages and another that parses them. Simple, common. I use ArrayBlockingQueue for synchronization, but don't want the dispatcher to directly access workers message queue - I use a wrapper. The question is if the setter should be declared synchronized.

public class Worker implements Runnable{
    protected final ArrayBlockingQueue<ByteBuffer> messages = new ArrayBlockingQueue<ByteBuffer>(16);

    public synchronized void putMessage(ByteBuffer msg) throws InterruptedException{
        messages.put(ByteBuffer);
    }
}

Upvotes: 4

Views: 660

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

The putMessage method would have to be synchronized if only one thread at a time needed to access a non-thread-safe shared state inside this method (or would have to make several modifications on a shared state atomically).

All the method does is to call a method on an ArrayBlockingQueue, which is designed precisely to be accessed concurrently by several threads.

The method doesn't need to be synchronized.

Upvotes: 6

Related Questions