When should weak references be used?

后端 未结 4 1612
南方客
南方客 2020-12-08 16:21

I recently came across a piece of Java code with WeakReferences - I had never seen them deployed although I\'d come across them when they were introduced. Is this something

4条回答
  •  离开以前
    2020-12-08 16:47

    You use them whenever you want to have a reference to an object without keeping the object alive yourself. This is true for many caching-like features, but also play an important role in event handling, where a subscriber shall not be kept alive by being subscribed to an event.

    A small example: A timer event which refreshes some data. Any number of objects can subscribe on the timer in order to get notified, but the bare fact that they subscribed on the timer should not keep them alive. So the timer should have weak references to the objects.

提交回复
热议问题