Java Object Build Cache

Java object reference + ReferenceQueue implements the cache of Java objects

  • Strong, soft, weak and virtual references of Java objects (making the program more flexible to control the life cycle of objects):
    1. Strong Reference: The most common reference, the object has a strong reference, and the memory space is insufficient, the JVM would rather throw OutOfMemoryError error, GC will never recycle it.
    2. Soft Reference: If the object only has soft references and the memory space is sufficient, the GC will not reclaim it; if the memory space is insufficient, the memory of these objects will be reclaimed. Soft references enable memory-sensitive caching.
    3. Weak reference (WeakReference: The difference compared to soft reference is that even if there is enough memory space, GC will recycle the weak reference object. Since GC is a lower priority thread, weak reference will not be found quickly.
      Weak reference is the same as Soft reference can be used in conjunction with a reference queue (ReferenceQueue), if the object referenced by the reference is reclaimed by GC, the JVM will add the reference to the reference queue associated with it.
    4. PhantomReference: used to track objects Before being reclaimed by GC, the virtual reference must be used in conjunction with the reference queue (ReferenceQueue). When the garbage collector is about to reclaim an object, if it finds that it has a virtual reference, it will add the virtual reference to the memory before reclaiming the object. into the reference queue associated with it.

  • Judgment of Java object accessibility:
      ◆Single reference path accessibility judgment: In this path, the weakest reference determines the accessibility of the object
      ◆Multiple reference path accessibility judgment: Among several paths, the most A strong reference determines the accessibility of an object

  • Use soft references to build a cache of sensitive data (the key is that the JVM reclaims soft accessible objects before the virtual machine throws OutOfMemoryError):
      SoftReference is characterized in that an instance of it holds a soft reference to a Java object, and the existence of the soft reference does not prevent it The garbage collection thread reclaims the Java object. That is to say, once the SoftReference saves a soft reference to a Java object, the get() method provided by the SoftReference class returns a strong reference to the Java object before the garbage thread recycles the Java object. Also, the get() method will return null once the Java object is reclaimed by the garbage thread.
      MyObject aRef = new MyObject();
      SoftReference aSoftRef=new SoftReference(aRef);
    When we end aReference's strong reference to this MyObject instance: aRef = null, this MyObject object becomes a soft accessible object, and the JVM reclaims the soft accessible object as Before the virtual machine throws OutOfMemoryError, and the soft-reachable objects that have not been used for a long time are preferentially recycled, the "new" soft-reversible objects that have just been used will be retained by the virtual machine as much as possible. Before recycling these objects, we can regain a strong reference to the instance by: MyObject anotherRef=(MyObject)aSoftRef.get();

  • Use ReferenceQueue to clear the SoftReference that has lost the soft reference object:
    1.SoftReference object has the generality of Java object in addition to the speciality of saving soft reference.
    2. When the soft-reachable object is recycled, although the get() method of the SoftReference object returns null, the SoftReference object no longer has the value of existence, and an appropriate clearing mechanism is needed to avoid the memory brought by a large number of SoftReference objects. leakage.
    3. ReferenceQueue is also provided in the java.lang.ref package. If a ReferenceQueue object is used as a parameter to provide the SoftReference constructor when creating the SoftReference object.
    4. At any time, we can call the poll() method of the ReferenceQueue to check whether any non-strongly reachable objects it cares about are recycled. If the queue is empty, it will return a null, otherwise the method returns a Reference object in front of the queue.
    5. Using this method, we can check which SoftReference soft referenced object has been reclaimed. So we can clear these SoftReference objects that lose the soft referenced objects.

    ReferenceQueue queue = new  ReferenceQueue();  
    SoftReference  EmployeeRef=new  SoftReference(aMyObject, queue);  
    SoftReference ref = null;  
    while ((ref = (EmployeeRef) q.poll()) != null) {  
        // 清除ref  
    }  

Use weak references to build caches of non-sensitive data (memory leak caused by global Map, fix SocketManager with WeakHashMap.):
The most common cause of unintentional object retention is to use Map to associate metadata with transient objects. An object is assumed to have a medium lifetime, longer than the method call that allocated it, but shorter than the application's lifetime, such as a client's socket connection. Some metadata needs to be associated with this socket, such as the identity of the user who made the connection. This information is not known when the Socket is created, and data cannot be added to the Socket object because there is no control over the Socket class or its subclasses. At this time, the typical approach is to store this information in a global Map, as shown in the SocketManager class below: Use a global Map to associate metadata with an object. Preventing leaks in SocketManager is easy, just replace HashMap with WeakHashMap. (It is assumed here that the SocketManager does not need to be thread-safe). This approach can be used when the lifetime of the map must be tied to the lifetime of the key.

public class SocketManager {  
    private Map<Socket,User> m = new WeakHashMap<Socket,User>();  
    public void setUser(Socket s, User u) {  
        m.put(s, u);  
    }  
    public User getUser(Socket s) {  
        return m.get(s);  
    }  
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325579367&siteId=291194637