Finding Memory Usage in Java

后端 未结 8 2313
野趣味
野趣味 2021-02-09 13:52

Following is the scenario i need to solve. I have struck with two solutions.

I need to maintain a cache of data fetched from database to be shown on a Swing GUI. Wheneve

相关标签:
8条回答
  • 2021-02-09 14:10

    The usual way to handle this sort of thing is to use WeakReferences and SoftReferences. You need to use both - the weak reference means you are not holding multiple copies of things, and the soft references mean that the GC will hang onto things until it starts running out of memory.

    If you need to do additional cleanup, then you can add references to queues, and override the queue notification methods to trigger the cleanup. It's all good fun, but you do need to understand what these classes do.

    0 讨论(0)
  • 2021-02-09 14:22

    I've only used the first method for similar task and it was OK.

    One thing you should note, for both methods, is to implement some kind of debouncing - i.e. once you recognize you've hit 70% of memory, wait for a minute (or any other time you find appropriate) - GC can run at that time and clean up lots of memory.

    If you implement a Runtime.freeMemory() graph in your system you'll see how the memory is constantly going up and down, up and down.

    0 讨论(0)
提交回复
热议问题