1

I have been trying to find a Java queue implementation with a special size limit. In contrast to the usual size parameter that limits the count of objects in the queue, I need to limit the queue's maximum memory usage (in bytes). The queue would be used to hold objects of very different sizes, some huge and some very small. I.e. the queue would hold only small amount of large objects and bigger amount of smaller objects.

Another possibility would be a queue with a size parameter in insert methods. When adding a new element to the queue I could specify how big the object to be added is.

Would anyone know of such Java queue implementation?

Thanks!

mins
  • 6,478
  • 12
  • 56
  • 75
  • Welcome to Stackoverflow. Share the code you have tried yet. – Nagama Inamdar Apr 06 '15 at 11:00
  • Please take a look at [this](http://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object) previous SO question. Once you follow those rules, you should be in a position to create the data structure you are after. – npinti Apr 06 '15 at 11:02
  • 1
    it will be **very** slow and potentially rather inaccurate to attempt to calculate memory usage. There is no feasible way to do this if you want any sort of performance. – Boris the Spider Apr 06 '15 at 11:05
  • Getting memory usage of an arbitrary Java object is extremely difficult and expensive. You're better off finding some other metric to limit. – Louis Wasserman Apr 06 '15 at 18:39

1 Answers1

1

https://github.com/ehcache/sizeof

<dependency>
  <groupId>org.ehcache</groupId>
  <artifactId>sizeof</artifactId>
  <version>0.3.0</version>
</dependency>

This library gives you a way of checking the size of your queues:

private SizeOf sizeOf = SizeOf.newInstance();
sizeOf.deepSizeOf(someQueue)

In the add method of your implementation class always check the size of the queue using sizeOf.deepSizeOf and if this value exceeds your expected limit throw an IllegalStateException or handle the error otherwise.

fresskoma
  • 25,481
  • 10
  • 85
  • 128
Amod Pandey
  • 1,336
  • 3
  • 14
  • 22