Search code examples
javamultithreadingconcurrencythread-safetyjava.util.concurrent

Can ConcurrentLinkedDeque have a fixed size and overwrite old elements?


If I got this right ConcurrentLinkedDeque acts as a stack right if you use pollLast() ?

Now my issue is that I need a set size of ConcurrentLinkedDeque. My producer doesn't stop, so even if I have 16GB of ram I will run out eventually. SO is it possible to se a fixed size ?

My implementation:

ConcurrentLinkedDeque<String> queue = new ConcurrentLinkedDeque<>();

Producer (Thread 1): runs queue.add(line); Consumer (Thread 2): runs queue.pollLast();

Please note that both threads run in a while true loop. This is because of the requirements. That is why I am using ConcurrentLinkedDeque and not ArrayBlockingQueue or SynchronousQueue because it is non-blocking.

Also do I need to declare anything synchronised ?


Solution

  • Can ConcurrentLinkedDeque have a fixed size?

    No, it's "an unbounded concurrent Deque based on linked nodes."

    Do I need to declare anything synchronised?

    ConcurrentLinkedDeque itself is thread-safe. Synchronisation is required only for composite actions (like overwriting old elements).

    Can ConcurrentLinkedDeque overwrite old elements?

    I don't think there is such a method. That's a composite action that requires

    • remembering the position of an element you are going to change and all the elements that come before/after;
    • changing the element;
    • restoring the order (putting the elements back).

    These three actions should be performed within a synchronized block.