Java theory and practice: blocking memory leaks with weak references — reprint

To make objects that are no longer used by the garbage collection (GC) collector, the logical life cycle of the object (the time the application uses it) and the actual life cycle of the reference to the object must be the same. Most of the time, good software engineering technology ensures that this is implemented automatically without us paying too much attention to the object life cycle. However, occasionally, we create a reference that contains the object in memory for a much longer time than we expected This situation is called unconscious object retention.

The most common reason for unconscious object retention is to use map to associate metadata with temporary objects (transient object). It is assumed that an object has a medium life cycle, which is longer than the life cycle of the method call to which it is assigned, but shorter than the life cycle of the application, such as the socket connection of the client. Some metadata needs to be associated with the socket, such as the identity of the user generating the connection. This information is not known when the socket is created, and You cannot add data to the socket object because you cannot control the socket class or its subclasses. At this time, the typical method is to store this information in a global map, as shown in the socketmanager class in Listing 1:

m = new HashMap (); public void setUser(Socket s,User u) {
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>