-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

Java 9 Concurrency Cookbook, Second Edition
By :

Java has a special kind of thread called daemon thread. When daemon threads are the only threads running in a program, the JVM ends the program after finishing these threads.
With these characteristics, daemon threads are normally used as service providers for normal (also called user) threads running in the same program. They usually have an infinite loop that waits for the service request or performs the tasks of a thread. A typical example of these kinds of threads is the Java garbage collector.
In this recipe, we will learn how to create a daemon thread by developing an example with two threads: one user thread that would write events on a queue and a daemon thread that would clean the queue, removing the events that were generated more than 10 seconds ago.
The example for this recipe has been implemented using the Eclipse IDE. If you use Eclipse or a different IDE, such as NetBeans, open it and create a new Java project.
Follow these steps to implement the example:
Event
class. This class only stores information about the events our program will work with. Declare two private attributes: one called the date of the java.util.Date
type and the other called the event of the String
type. Generate the methods to write and read their values.WriterTask
class and specify that it implements the Runnable
interface:public class WriterTask implements Runnable {
private Deque<Event> deque; public WriterTask (Deque<Event> deque){ this.deque=deque; }
run()
method of this task. This method will have a loop with 100 iterations. In each iteration, we create a new event, save it in the queue, and sleep for 1 second:@Override public void run() { for (int i=1; i<100; i++) { Event event=new Event(); event.setDate(new Date()); event.setEvent(String.format("The thread %s has generated an event", Thread.currentThread().getId())); deque.addFirst(event); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } }
CleanerTask
class and specify that it extends the Thread
class:public class CleanerTask extends Thread {
setDaemon()
method:private Deque<Event> deque; public CleanerTask(Deque<Event> deque) { this.deque = deque; setDaemon(true); }
run()
method. It has an infinite loop that gets the actual date and calls the clean()
method:@Override public void run() { while (true) { Date date = new Date(); clean(date); } }
clean()
method. It gets the last event, and if it was created more than 10 seconds ago, it deletes it and checks the next event. If an event is deleted, it writes the message of the event and the new size of the queue so you can see its evolution:private void clean(Date date) { long difference; boolean delete; if (deque.size()==0) { return; } delete=false; do { Event e = deque.getLast(); difference = date.getTime() - e.getDate().getTime(); if (difference > 10000) { System.out.printf("Cleaner: %s\n",e.getEvent()); deque.removeLast(); delete=true; } } while (difference > 10000); if (delete){ System.out.printf("Cleaner: Size of the queue: %d\n", deque.size()); } }
main
class. Create a class called Main
with a main()
method:public class Main { public static void main(String[] args) {
Deque
class:Deque<Event> deque=new ConcurrentLinkedDeque<Event>();
WriterTask
threads as available processors have the JVM and one CleanerTask
method:WriterTask writer=new WriterTask(deque); for (int i=0; i< Runtime.getRuntime().availableProcessors(); i++){ Thread thread=new Thread(writer); thread.start(); } CleanerTask cleaner=new CleanerTask(deque); cleaner.start();
If you analyze the output of one execution of the program, you would see how the queue begins to grow until it has a size of, in our case, 40
events. Then, its size will vary around 40
events it has grown up to until the end of the execution. This size may depend on the number of cores of your machine. I have executed the code in a four-core processor, so we launch four WriterTask
tasks.
The program starts with four WriterTask
threads. Each thread writes an event and sleeps for 1 second. After the first 10
seconds, we have 40
events in the queue. During these 10
seconds, CleanerTask
are executed whereas the four WriterTask
threads sleep; however, but it doesn't delete any event because all of them were generated less than 10
seconds ago. During the rest of the execution, CleanerTask
deletes four events every second and the four WriterTask
threads write another four; therefore, the size of the queue varies around 40
events it has grown up to. Remember that the execution of this example depends on the number of available cores to the JVM of your computer. Normally, this number is equal to the number of cores of your CPU.
You can play with time until the WriterTask
threads are sleeping. If you use a smaller value, you will see that CleanerTask
has less CPU time and the size of the queue will increase because CleanerTask
doesn't delete any event.
You only can call the setDaemon()
method before you call the start()
method. Once the thread is running, you can't modify its daemon status calling the setDaemon()
method. If you call it, you will get an IllegalThreadStateException
exception.
You can use the isDaemon()
method to check whether a thread is a daemon thread (the method returns true
) or a non-daemon thread (the method returns false
).