Garbage Collection - How to manually collect objects in java
为情所困
为情所困 2017-05-17 10:05:31
0
5
1064

Let’s start with the code first. My goal is to make the data disappear completely

public class Test {
    public static void main(String[] args) {
        Data data = new Data();
        data.num = 10;

        Data new1 = data;
        Data new2 = data;
        new2 = null;
        data = null;
        System.out.println(new1.num);
    }

}

class Data {
    int num;
}

I know Java's garbage collection mechanism. As long as something is still referencing it, it will not disappear. The above code can still output 10 normally.
But I want to know how to do it so that System.out.println(new1.num);Throws a null exception, that is, there is no such data at all
Don’t say just letnew1=null

为情所困
为情所困

reply all(5)
迷茫

You said it yourself, "I know Java's garbage collection mechanism. As long as something is still referencing it, it will not disappear." The variable "new1" is still referencing the memory of "new Data()" in the heap. , how can it be allowed to be recycled, so that the code we write is not all null pointer exceptions. You can use WeakReference instead of strong reference.

    WeakReference<Data> new1 = new WeakReference(data);
    Data new2 = data;
    new2 = null;
    data = null;
    System.gc();//告诉垃圾收集器打算进行垃圾收集,而垃圾收集器进不进行收集是不确定的 ,所以下面延迟2秒
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println(new1.get().num);
我想大声告诉你
System.gc();

It is recommended that the JVM perform gc, which may be completely rejected. The GC itself will run automatically periodically, and the JVM determines the timing of the run. Moreover, the current version has a variety of smarter modes to choose from, and will automatically make selections based on the machine it is running on, even if there are indeed performance improvements. If required, you should also fine-tune the GC operating mechanism instead of optimizing performance by using this command.

Ty80

Objects that have object references and are about to be deleted can still be set to null

    {
        OutClass outClass1 = new OutClass();
        OutClass outClass2 = new OutClass();
        outClass2.outClass = outClass1;
        outClass1 = null;
        System.out.print(outClass1);
    }
    
    class OutClass {
        public OutClass outClass;
    }
左手右手慢动作

Before you understand the principles of JMM, never use System.gc() indiscriminately, just obj=null; when the object is used up.

滿天的星座

The answer is no. This is undefined behavior in the JVM specification. Developers should not try to manually help the virtual machine recycle an object. If it is Sun's JDK, there seems to be an unsafe package, but I have never used it and I don't know if there is such an API.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template