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
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.
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.
Objects that have object references and are about to be deleted can still be set to null
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.