Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safe queue in Java

I want to implement a queue, that is hit by multiple threads.

This is stack is in a singleton class.

Now, a simple solution is to synchronize this? I assume it would need this as standard? However, I want to prioritize writing to it.

So, write is high priority, read is low priority.

Is this possible?
Ideally writing by multiple threads without synchronizing would be great, if possible.

like image 765
Matthew Smith Avatar asked Jan 11 '13 14:01

Matthew Smith


1 Answers

Why do you want to avoid synchronizing? It's possible to write "lock-free" structures, but it's quite tricky and easy to get wrong.

If I were you, I'd use ArrayBlockingQueue or ConcurrentLinkedQueue (or one of the other structures from java.util.concurrent) and make your life easy!

Oh, and I missed the bit about prioritising reads over writes. You can do that with the ReentrantReadWriteLock class. Then you don't need a thread-safe queue - you just lock externally using the read-write lock depending on whether you're reading or writing.

like image 101
dty Avatar answered Sep 18 '22 07:09

dty