Do I need to synchronize ArrayBlockingQueue methods?

I have two threads: one that sends messages, and the other that analyzes them. Simple, general. I use ArrayBlockingQueue for synchronization, but I do not want the dispatcher to directly access the work message queue - I use the shell. The question is whether the installer should declare 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); } } 
+4
source share
1 answer

The putMessage method should be synchronized if only one thread at a time was to access the unsafe general state inside this method (or had to make several changes in the general state atomically).

All that the method does is call the method on an ArrayBlockingQueue , which is intended for simultaneous access by multiple threads.

The method does not need to be synchronized.

+6
source

Source: https://habr.com/ru/post/1394765/


All Articles