Will all the soft references in java be cleared in one single shot?

316 Views Asked by At

I read this article and now I'm clear about what is the basic difference between weak and soft references. I also understand that unlike weak references (which will cause the object to be collected in the next GC cycle if no strong references are there to that object), soft references are kept in memory until JVM runs out of memory.

But the question I have is if JVM runs out of memory and Garbage Collector starts collecting the soft references also, it should logically collect all the existing objects with soft references (my guess). Am I right about this?

Another thing that comes to my mind is that soft references have a very good use case, that is in-memory caches. But if all the soft references that I have will all be cleared in one single shot by GC, then it may not be the expected thing that we always want.

Is there a way to control the percent of soft-references that will be cleared? Or can we tell the GC to stop clearing the soft-references once it has recovered some specific amount of memory?

I'm asking this for the sake of getting a good grip on how soft references can be used effectively, and obviously no one will want their cache to be completely evicted from memory even when you need a very small amount of memory.

1

There are 1 best solutions below

3
On BEST ANSWER

More of an informal answer here:

First of all, it is not necessary logical to collect all soft references immediately. Theoretically, the JVM could (additionally) track last usage, or some usage counter. And make decisions based on that (to first clear only soft references that are "older" or "less used"). Or it orders soft references by the actual amount of memory the reference "links" to.

Beyond that, the JVM might operate on fixed memory increments. Meaning: why throw out soft references for 500 MB of memory, when you only need/want 50 MB?!

In other words: clearing all soft references is simple the "most easy to implement" strategy, but not necessary the only option. A JVM could be free to implement all sorts of strategies. For example one that tries to remove as few soft references as possible, in order to specifically support in-memory caches!

So unless some other answer can show the JLS section that clearly states that they should all be cleared in one shot, you should not drive conclusions based on your "perception" of what is logical.