Michael Berry
Michael Berry

Reputation: 72344

Uses of different reference types in Java

I've recently been playing around with soft, weak and phantom reference types in Java and have been wondering if there's any uses out there for them that I haven't come across. I've used them in the past for various things and they've always fallen under the category of the following:

However, there's only 3 uses there and I daresay there's lots more things that they might be useful for which I've never come across. All suggestions welcome!

Upvotes: 4

Views: 1478

Answers (1)

maaartinus
maaartinus

Reputation: 46482

Two strange ideas:

  • You may use a soft reference for finding out you're low on memory and manually freeing some caches which themselves can't use soft references.
  • You may use a weak reference to find out when the GC runs, which may be useful in case you're experiencing strange program pauses which may or may not be related to the GC.

IMHO, in some (rare) cases weak references may be better for caching, e.g., you may weakly refer to values, which are improbable to be needed again once they get removed from the structures using them (i.e., they get strongly unreachable). Moreover, there's a serious bug in the JVM concerning soft references, which may force you to do so.

Upvotes: 1

Related Questions