Monday, January 30, 2012

Daemon Threads in Java

In normal circumstances, a Thread in executed until either it reaches the end of its void run() method or until void stop() is called (this method is deprecated and it's not recommended to use because it may trigger ThreadDeath errors).

Daemon threads are service providers for user-created threads. The main difference between daemon threads and non-daemon threads is that an application will end if the only remaining threads are daemon threads. The application will not end if there is at least one non-daemon thread running.

Any thread can become a daemon thread if one uses the method void setDaemon(boolean isDaemon). It is imperative to call this method before starting the thread. To check if a thread is a daemon thread you can simply call the method boolean isDaemon().

Also, it is to note that the void run() method must contain an infinite loop if you want your daemon thread to provide services as long as your application is opened.

Here's an example:
public class DaemonThread extends Thread
{
 public DaemonThread(String name)
 {
  super(name);
  this.setDaemon(true);
  this.start();
 }
 
 public void run()
 {
  while(true) //Keeps the daemon running
  {
   System.out.println("I am the Daemon " + getName() + "!");
   try 
   {
    Thread.sleep(100);
   } catch (InterruptedException e){}
  }
 }
}

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger