Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to a thread when the original class goes out of scope

I simplified the example below for the sake of clarity, but I came across this in a live production program and I cannot see how it would be working!

public class Test
{
    static void Main() 
    {
        Counter foo = new Counter();
        ThreadStart job = new ThreadStart(foo.Count);
        Thread thread = new Thread(job);
        thread.Start();
        Console.WriteLine("Main terminated");
    }
}

public class Counter
{
    public void Count()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("Other thread: {0}", i);
            Thread.Sleep(500);
        }
        Console.WriteLine("Counter terminated");
    }
}

The main routine starts the counter thread and the main routine terminates. The counter thread carries on regardless giving the following output.

Main terminated    
Other thread: 0
Other thread: 1
Other thread: 2
Other thread: 3
Other thread: 4
Other thread: 5   
Other thread: 6
Other thread: 7    
Other thread: 8    
Other thread: 9
Counter terminated

My example program demonstrates that although the calling class no longer exists, the thread survives to completion. However, my understanding is that once a class is out of scope, its resources will eventually be tidied up by garbage collection.

In my real life scenario, the thread does a mass Emailing lasting 1-2 hours. My question is "Would garbage collection eventually kill off the thread or will GC know that the thread is still processing"? Would my Emailing thread always run to completion or is there a danger it will terminate abnormally?

like image 882
MortimerCat Avatar asked May 18 '15 20:05

MortimerCat


People also ask

Does a thread automatically be killed?

A thread is automatically destroyed when the run() method has completed. But it might be required to kill/stop a thread before it has completed its life cycle. Previously, methods suspend(), resume() and stop() were used to manage the execution of threads.

How do you know when a thread has finished?

Use Thread. Join(TimeSpan. Zero) It will not block the caller and returns a value indicating whether the thread has completed its work.

What is thread scope in Java?

Thread local can be considered as a scope of access like session scope or request scope. In thread local, you can set any object and this object will be local and global to the specific thread which is accessing this object. Java ThreadLocal class provides thread-local variables.


1 Answers

From System.Threading.Thread

It is not necessary to retain a reference to a Thread object once you have started the thread. The thread continues to execute until the thread procedure is complete.

So even if the Thread object is unreferenced, the thread will still run.

like image 139
xanatos Avatar answered Oct 04 '22 13:10

xanatos