When is a thread in Java removed from memory?

From the Java API API document:

The Java virtual machine continues to execute threads until the following takes place:

All threads that are not daemon threads died either by returning from a call to the run method or by throwing an exception that extends beyond the run method.

I hope my assumption is true that after the thread completes its run() method, it will get the right to garbage collection. In the same context, I'm just curious to know:

  • If he does not get the right to collect garbage after returning from run() , should a link be set to null for this?
  • The right to garbage collection does not necessarily mean that the object will be deleted from memory. This is the base operating system / JVM of its choice, when it is garbage collection. But how can one be sure (either through a Java program or an external tool) that the object is completely deleted from memory?
  • If a thread is considered dead after completion of its run () method, why can I execute isAlive() or getState() on the same thread object? Both calls return false and RUNNABLE respectively.
+6
source share
6 answers

The Thread class is a proxy for a real thread that is in its own memory.

I hope my assumption is true that after the thread completes its run () method, it will become suitable for garbage collection.

Actually there is some code after execution (), this code handles uncaught exceptions.

As soon as the thread dies, its own memory and stack are freed immediately, without requiring a GC. However, a Thread object is like any other object, and it lives until the GC has decided that it can be free, for example. no strong reference to it.

Similarly, FileOutputStream is a proxy for a file in the operating system. You can still reference the object even after the file has been close() or even deleted.

If after returning from run () it does not become suitable for garbage collection, do I need to set a reference to null for it?

You rarely have to do it anywhere. In fact, it is often easier not to refer to the stream in the first place or to use the ExecutorService to manage your streams.

When I have an object with a Thread field, I often die when this object dies, so the field should not be null ed out.

I also use the built-in thread pool used for Fork / Join. This is an easier way to perform tasks in a background thread, since it does not create or destroy threads.

 ExecutorService fjp = ForkJoinPool.commonPool(); 

The right to garbage collection does not necessarily mean that the object will be deleted from memory. It is at the sole discretion of the underlying operating system / JVM when it is garbage collection. But how can one verify (either through a Java program or an external tool) that the object is completely deleted from memory?

You cannot and should not try at all. GC will clean resources when necessary.

If a thread is considered dead as soon as it completes its run () method, why can I still execute isAlive () or getState () on the same thread object? Both calls return false and RUNNABLE respectively.

A stream object is like any other object. You can call methods on it as long as you keep a reference to it.

+8
source

It seems that you are disconnected from a common trap with indispensable threads in Java: the thread itself is not a Java object. This is a native resource (thread of execution). It will be “deleted from memory” as soon as it finishes executing its code.

A Thread instance, on the other hand, is just an ordinary Java object with the same life cycle as any other & mdash object, with the exception of the additional rule that it remains reachable, at least as long as the native thread lives, This is implied by the fact that you can always call Thread.currentThread() .

So, if you keep a reference to the Thread instance that is responsible for the dead thread, it will not magically disappear, and all of its methods will continue to work as indicated. You can hold on to her as much as you need.

As for your question 2, “deleting” an object from memory is an almost meaningless term. The runtime itself does not actually know about the collected objects - these are the ones that it forgot about.

+4
source

The fact that the thread has completed execution does not alter the validity of the object reference. While you hold this link, the Thread object cannot be garbage collected.

This means that as long as you hold a link to Thread, you can name things like isAlive . When you release all links, Thread can be garbage collected.

If you want to have a reference to an object without preventing this garbage collection, you should use a WeakReference . When you use such a link, you should check if the link to the object exists.

+3
source

With respect to threads, there are two things.

  • Before and during startup, flow objects themselves are the roots of the GC, that is: they and any objects that can be accessed from them cannot be assembled.
  • As soon as the thread ends, it "returns" to the regular object. The same GC rules apply to them as for any other object. So, for example, as long as you have a strong reference to them, they will not be compiled, and yes, you can call methods on them without problems.

So, my advice is to treat dead threads, for example, for an object like List or Map . What applies to them refers to those threads that have finished working.

+2
source

If after returning from run () it does not become suitable for garbage collection, should its link be set to null for this?

It is always better to explicitly point objects to zero (if you are sure that they will not be used in the future) to facilitate work with the GC.

 class Test { protected void finalize() throws Throwable { System.out.println("test finalized"); }; public static void main(String[] args) { Thread t = new MyThread(); t.start(); Test test = new Test(); try { System.out.println(t.getState()); // t.join(); t = null; test = null; // System.out.println(t.getState()); Thread.sleep(500); // change this to say 2 or 3 sec ie, until run() completes. The thread object will be finalized System.gc(); System.out.println("gc call done.."); Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 

}

 class MyThread extends Thread { protected void finalize() throws Throwable { System.out.println("MyThread instance finalized.."); }; @Override public void run() { for (int i = 0; i < 5; i++) { try { Thread.sleep(300); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(i); } } 

}

O / P: case: 1 → if the thread executes when gc is called.

 RUNNABLE 0 gc call done.. test finalized 1 2 3 4 

case: 2 -> IF thread terminated when gc call is made.

  RUNNABLE 0 gc call done.. test finalized 1 2 3 4 MyThread instance finalized.. 

Having the right to garbage does not necessarily mean that the object will be deleted from memory. It is at the sole discretion of the underlying operating system / JVM when it is garbage collection. But how can one (either through a Java program or an external tool) make sure that the object is completely deleted from memory?

In Java, you can only tell when an object becomes inaccessible (not GCed, unreachable.). finalize() will be called when your onjecy becomes unavailable.

If a thread is considered dead as soon as it finishes its run () method, why can I still execute isAlive () or getState () on the same thread object? Both calls return false and RUNNABLE respectively. “The thread may have completed execution.” But he will still be able to. discontinued condition. You call these methods on a thread instance. Thus, it still contains some status data.

+1
source

I believe that the garbage collector collects an object when there are no references to the object in memory. In the case of a stream, the process is running, so stream objects will not be collected by the garbage collector.

Each object tree must have one or more root objects. While the application can reach these roots, the entire tree is accessible through

 javabook.compuware.com/content/memory/how-garbage-collection-works.aspx 
0
source

Source: https://habr.com/ru/post/981971/


All Articles