I'm running out of memory in Java due to some very large Lists and Sets built up over the course of a transaction and iterated over just once at transaction's end. Are there any libraries that provide Java collections that can spool their serializable contents to disk when the collection size exceeds a given threshold?
You could try something like ehcache and its overflowToDisk option
I won't post you example code because it would become too long, but this is how I done it before:
LinkedBlockingQueue
.offer
, put
, poll
, take
and remove
methods. Example: if superclass' offer
returns false (capacity reached), then I would start serializing to disk.take
implementation, you check if you have any present elements in memory at all, and, if not, then you start reading from disk (and removing the first record read because it will now reside in memory; or you can read records in batches, of course).That way, 99% of your disk-serialized queue is ready, and you only put your extra functionality at exactly the right spots. You would need to thoroughly read the documentation of Java's BlockingQueue
interface, but hey, it's worth your time because you will only add that little extra bit of functionality you need, rather than writing the whole thing from scratch.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With