开发者

Uses of different reference types in Java

开发者 https://www.devze.com 2023-02-05 16:06 出处:网络
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 t

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:

  • Using phantom references in place of finalizers - I prefer this since there's 0 chance of a dead object being resurrected
  • Using weak references in a hashmap t开发者_高级运维o hold an object=>value mapping, where the mapping should only be in place if an object exists elsewhere (useful when needing to add extra information to an object in a library for instance whose source can't be modified)
  • Using soft references for caching (works much better than weak references because the JVM keeps them around for much longer and only lets go if it feels it needs to.)

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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号