LIFO queue that will drop old elements when needed.

The Idea

Have a Last-In-First-Out queue (implements java.util.Queue<E>) that will release old elements so that garbage collection (GC) can remove them. Like a cache that is a stack.

Example: Undo Queue

A simple desktop app could have a queue of actions, so that the user can undo the last steps. In the settings the user can set how many actions can be undone. Lets say the users wants to be able to undo 20 actions. But that doesn’t mean we have to remove older actions as soon as the user has done more than 20. We can keep them in the queue, but use SoftReference. So GC can just remove them when the memory is actually full. But the queue makes sure the 20 newest actions are always protected from GC.

You can change the limit of the queue at any time.

Example: In Memory Log

Imagine you need a log with messages that get less relevant the older they are. The application keeps adding new messages all the time and you want to keep as many as possible. Insertion order is obviously important and usually you only want to iterate the last few messages. Sometimes you want to dump them all into a text file.

So you can create a WeakAssQueue which will use a limit for the elements that are not protected. Whenever the JVM is running out of memory it will remove those oldest elements. Make sure the limit is large enough so that removing them will actually free enough memory. All the others will still remain in memory and can be used. However, if some other component of the same application uses lots of memory it can happen that your log gets emptied completely.

The Name

I just call it weak ass list because it sounds funny. We can say that a list has a head (first element) and a tail (further elements). In this case it has an ass that can be removed at any time.

You probably would not actually use weak references, because in most cases soft references are more useful. So maybe SoftTailQueue would make more sense.

The Code

The Code is on GitHub: gist.github.com/claudemartin/9977caba94e1d8d97edf4b0435d8fea4

All you need is WeakAssQueue.java and you can just add a namespace (Java package). If you plan on working on the code you can also get the JUnit tests, which are in the second file.

Leave a Reply

Your email address will not be published. Required fields are marked *