Implementing a queue with a blocked "take ()" but with an eviction policy

Is there an implementation with a blocking queue for acceptance, but is limited by the maximum size. When the size of the queue reaches the specified maximum size, instead of a "put" lock, it removes the head element and inserts it. So put is not locked (), but take () is.

One use is that if I have a very slow consumer, the system will not crash (running out of memory), rather, this message will be deleted, but I do not want to block the manufacturer.

An example of this is the stock trading system. When you get a surge in stock / quotes trading data, if you haven’t consumed the data, you want to automatically throw away the old trading / stock quotes.

+3
source share
2 answers

There is currently no thread safe queue in Java that will do what you are looking for. However, there is a BlockingDequeue (Double Ended Queue) in which you can write a wrapper in which you can take from the head and tail, as you see freely.

This class, similar to BlockingQueue, is thread safe.

+1
source

ThreadPoolExecutor has several strategies. Find "AbortPolicy" in this javadoc . You can also implement your own policies if you wish. Perhaps Discardsimilar to what you want. Personally, I think that CallerRunsis what you want in most cases.

, , , , , . , LinkedList - synchronize.

EDIT: ( ..) "" - , . / java. , . , - , OOME ( ).

+1

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


All Articles