How can I atomize "enqueue if free space OR dequeue then enqueue" for a Java queue / list?

I have a requirement for a fixed capacity Java list, but which always allows threads to add items to the beginning. If it is full, it must remove the element from the end to make room. No other process will delete elements, but other processes will want to iterate over the elements.

Is there anything in the JDK that would allow me to do this atomically?

My current plan is to simply use some existing stream collections (like LinkedBlockingQueue) and then sync them when checking for capacity / add / remove. Will this work?

Thanks.

+3
source share
4 answers

Your idea will work, but will involve extracting multiple locks (see example below). Given the need to synchronize multiple operations when adding data, you can also wrap the implementation LinkedListfrom Queueto to avoid the overhead of additional locks .

// Create queue with fixed capacity.
Queue<Item> queue = new LinkedBlockingQueue<Item>(1000);

...

// Attempt to add item to queue, removing items if required.
synchronized(queue) { // First lock
  while (!queue.offer(item)) { // Second lock
    queue.take(); // Third lock
  }
}
+1
source

I work in the old version of Java (yes, 1.3, I have no choice), so even if it is there in later Javas, I cannot use it. Therefore, I encoded the following lines:

public class Fifo  {
 private LinkedList fifoContents = new LinkedList();
 public synchronized void  put(Object element) {
     if ( fifoContents.size() > 100){               
          fifoContents.removeFirst();                
          logger.logWarning("*** Backlog, discarding messaage ");
     }
     fifoContents.add (element);
     return;
 }

 public synchronized Object get() throws NoSuchElementException {
     return fifoContents.removeFirst();
 }
}
0
source

, // :

class DroppingQueue<E>
extends ArrayBlockingQueue<E> {
    public boolean add(E item) {
        while (! offer(item)) {
            take();
        }
        return true;
    }
}

, add offer , , , , # 1 offer, , # 2 , , , . , , .

0

JDK . ​​, head/tail - , .

0

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


All Articles