Question

I need some kind of a queue that will be synchronized for adding new elements and removing new elements:

Synchronization should be on adding elements, removing elements and between add/remove methods.

I thought of some options:
1. To find a thread safe queue implementations, which means that access to the queue no matter which method will call will block it --> Maybe not so clever..

2.Doing some wrapping of add/remove elements methods with synchronize on some lock object.--> This solution seems a bit ugly.

What are your opinions regard it?

Was it helpful?

Solution

I need some kind of a queue that will be synchronized for adding new elements and removing new elements:

You should use a BlockingQueue (for example ArrayBlockingQueue) which takes care of all of the synchronization for you. You call queue.add(...) to add to the queue and another thread would call take() to remove items from the queue.

OTHER TIPS

Or: 3. Use one of the BlockingQueues, which are thread safe, use lock-free algorithms and have blocking AND non-blocking methods.

For clever and not so ugly solution you need to write your own thread safe operation in some wrapper but instead of using synchronized you should use ReadWriteLocks. Anyway other nice option is Google guava library. You did not mention any bound/blocking operation need so i dont see BlockingQueue as good option. I recommend ConcurrentLinkedQueue of Guava which is an unbounded thread-safe queue based on linked nodes.

Hope this helps. For further details explore this link: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Queues.html

ConcurrentLinkedQueue page is : http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html?is-external=true

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top