17

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.

informatik01
  • 16,038
  • 10
  • 74
  • 104
Matthew Smith
  • 366
  • 2
  • 4
  • 16
  • 8
    Why don't you use something from `java.util.concurrent`? This is far from trivial, especially if lock-free. Locks are quite performant on modern JVMs and may easily beat, in a write-heavy setting, a lock-free solution based on transaction retries. – Marko Topolnik Jan 11 '13 at 14:19
  • 1
    There is `ConcurrentLinkedQueue` as a builtin. – fge Jan 11 '13 at 14:19

1 Answers1

26

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.

dty
  • 18,795
  • 6
  • 56
  • 82
  • Further thoughts, ArrayBlockingQueue looks perfect for my needs. I want to avoid synchronizing as I think it is causing significant slow downs when I try to scale up the threads (in this case users) on my system. – Matthew Smith Jan 11 '13 at 15:35
  • 14
    Stop thinking and start measuring. :-) – dty Jan 11 '13 at 15:36
  • 1
    The problem with ArrayBlockingQueue is well it blocks. What if you want the thread-safe queue without blocking caused by put() and take()? – JohnMerlino Jul 10 '14 at 01:37
  • 1
    @JohnMerlino you can still use offer() and poll(), which are non blocking. – Fabian Oct 23 '18 at 14:05