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.
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 .
LinkedList
Queue
// 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 } }
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(); } }
, // :
class DroppingQueue<E> extends ArrayBlockingQueue<E> { public boolean add(E item) { while (! offer(item)) { take(); } return true; } }
, add offer , , , , # 1 offer, , # 2 , , , . , , .
add
offer
JDK . , head/tail - , .
Source: https://habr.com/ru/post/1716180/More articles:Creating browser extensions - browserHow to prefix message length in TCP / IP - c ++Profile support for .NET Framework 3.5 SP1? - .netSetting how a form displays a field in a widget in django - djangoПроверить значение, чтобы отключить/включить пункт контекстного меню (android) - androidПоиск учебника htps для htps WCF - c#Capture closing tabs in Firefox extension - firefoxAlgorithm for converting a binary tree to a postfix mathematical expression? - algorithmJavaFx Offline Function? - javafxConvert SQL to LINQ to SQL - linq-to-sqlAll Articles