java - How to avoid memory leaks in callback? -


A third common source of memory leaks is listeners and other callback

. If you implement APIs where customers register callbacks but they do not clearly register, then unless you take any action, they will deposit. The best way to ensure that callbacks are immediately collected is garbage, for example, to store only weak references to them, by simply collecting them as Keys in WeakHashMap.

I am starting in Java. Can anyone teach me how to make poor references in callback and tell me how they solve memory leak problems? Thank you.

P> You can think of direct references as strong contexts, which do not require extra coding to create or access objects. In the remaining three types of references, the java.lang.ref package contains sub-classes of reference squares. Weak references are provided by the soft reference class, weaker references of WeakReference class, and Phantom Reference by Phantom Reference.

Soft reference data works like cache. When the system memory is low, the garbage collector can free an object whose only reference is a soft reference. In other words, if there is no solid reference to an object, then it is a candidate for the item release. Any soft reference is required to be released before the garbage collector is thrown out of an outmodel exposition.

Weak references are weaker than the soft contexts. If there is weak reference only in the context of an object, then the garbage collector can retrieve the memory used by the object at any time. There is no need for low memory conditions Usually, the memory used by the object is retrieved in the next passage of the garbage collector.

Fental reference is related to cleaning work. Garbage collector processes the final process and gives an alert immediately before releasing an object. Find out how to do cleanup tasks inside an object.

After the weak list model, which I will not post to avoid blocking this response.