Java 7 Concurrency Cookbook

By Javier Fernández González
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Thread Management

About this book

Java remains the global standard for developing various applications and enterprise software, and the launch of Java 7 brings with it exciting new capabilities for concurrent programming by way of the concurrency utilities enhancement. This allows developers to make the most of their applications with parallel task performance. "Java 7 Concurrency Cookbook" covers all elements of the Java concurrency API, providing essential recipes for taking advantage of the exciting new capabilities.On your computer, you can listen to music while you edit a Word document and read your emails, all at once! This is because your operating system allows the concurrency of tasks, much like the Java platform which offers various classes to execute concurrent tasks inside a Java program. "Java 7 Concurrency Cookbook" covers the most important features of the Java concurrency API, with special emphasis on the new capabilities of version 7. With each version, Java increases the available functionality to facilitate development of concurrent programs. This book covers the most important and useful mechanisms included in version 7 of the Java concurrency API, so you will be able to use them directly in your applications."Java 7 Concurrency Cookbook" includes recipes to enable you to achieve everything from the basic management of threads and tasks, to the new Fork /Join framework, through synchronization mechanisms between tasks, different types of concurrent tasks that Java can execute, data structures that must be used in concurrent applications and the classes of the library that can be customized.With the step-by-step examples in this book you’ll be able to apply the most important and useful features of the Java 7 concurrency API.

Publication date:
October 2012
Publisher
Packt
Pages
364
ISBN
9781849687881

 

Chapter 1. Thread Management

In this chapter, we will cover:

  • Creating and running a thread

  • Getting and setting thread information

  • Interrupting a thread

  • Controlling the interruption of a thread

  • Sleeping and resuming a thread

  • Waiting for the finalization of a thread

  • Creating and running a daemon thread

  • Processing uncontrolled exceptions in a thread

  • Using local thread variables

  • Grouping threads into a group

  • Processing uncontrolled exceptions in a group of threads

  • Creating threads through a factory

 

Introduction


In the computer world, when we talk about concurrency , we talk about a series of tasks that run simultaneously in a computer. This simultaneity can be real if the computer has more than one processor or a multi-core processor, or apparent if the computer has only one core processor.

All modern operating systems allow the execution of concurrent tasks. You can read your e-mails while you listen to music and read the news in a web page. We can say that this kind of concurrency is a process-level concurrency. But inside a process, we can also have various simultaneous tasks. The concurrent tasks that run inside a process are called threads .

Another concept related to concurrency is parallelism . There are different definitions and relations with the concurrency concept. Some authors talk about concurrency when you execute your application with multiple threads in a single-core processor, so simultaneously you can see when your program execution is apparent. Also, you can talk about parallelism when you execute your application with multiple threads in a multi-core processor or in a computer with more than one processor. Other authors talk about concurrency when the threads of the application are executed without a predefined order, and talk about parallelism when you use various threads to simplify the solution of a problem, where all these threads are executed in an ordered way.

This chapter presents a number of recipes that show how to perform basic operations with threads using the Java 7 API. You will see how to create and run threads in a Java program, how to control their execution, and how to group some threads to manipulate them as a unit.

 

Creating and running a thread


In this recipe, we will learn how to create and run a thread in a Java application. As with every element in the Java language, threads are objects . We have two ways of creating a thread in Java:

  • Extending the Thread class and overriding the run() method

  • Building a class that implements the Runnable interface and then creating an object of the Thread class passing the Runnable object as a parameter

In this recipe, we will use the second approach to create a simple program that creates and runs 10 threads. Each thread calculates and prints the multiplication table of a number between one and 10.

Getting ready

The example of this recipe has been implemented using the Eclipse IDE. If you use Eclipse or another IDE such as NetBeans, open it and create a new Java project.

How to do it...

Follow these steps to implement the example:

  1. Create a class named Calculator that implements the Runnable interface.

    public class Calculator implements Runnable {
  2. Declare a private int attribute named number and implement the constructor of the class that initializes its value.

      private int number;
      public Calculator(int number) {
        this.number=number;
      }
  3. Implement the run() method. This method will execute the instructions of the thread that we are creating, so this method will calculate the multiplication table of the number.

      @Override
      public void run() {
        for (int i=1; i<=10; i++){
          System.out.printf("%s: %d * %d = %d\n",Thread.currentThread().getName(),number,i,i*number);
        }
      }
  4. Now, implement the main class of the application. Create a class named Main that contains the main() method.

    public class Main {
      public static void main(String[] args) {
  5. Inside the main() method, create a for loop with 10 iterations. Inside the loop, create an object of the Calculator class, an object of the Thread class, pass the Calculator object as a parameter, and call the start() method of the thread object.

        for (int i=1; i<=10; i++){
          Calculator calculator=new Calculator(i);
          Thread thread=new Thread(calculator);
          thread.start();
        }
  6. Run the program and see how the different threads work in parallel.

How it works...

The following screenshot shows part of the output of the program. We can see that all the threads we have created, run in parallel to do their job, as shown in the following screenshot:

Every Java program has at least one execution thread. When you run the program, the JVM runs this execution thread that calls the main() method of the program.

When we call the start() method of a Thread object, we are creating another execution thread. Our program will have as many execution threads as calls to the start() method are made.

A Java program ends when all its threads finish (more specifically, when all its non-daemon threads finish). If the initial thread (the one that executes the main() method) ends, the rest of the threads will continue with their execution until they finish. If one of the threads use the System.exit() instruction to end the execution of the program, all the threads end their execution.

Creating an object of the Thread class doesn't create a new execution thread. Also, calling the run() method of a class that implements the Runnable interface doesn't create a new execution thread. Only calling the start() method creates a new execution thread.

There's more...

As we mentioned in the introduction of this recipe, there is another way of creating a new execution thread. You can implement a class that extends the Thread class and overrides the run() method of this class. Then, you can create an object of this class and call the start() method to have a new execution thread.

See also

  • The Creating threads through a factory recipe in Chapter 1, Thread Management

 

Getting and setting thread information


The Thread class saves some information attributes that can help us to identify a thread, know its status, or control its priority. These attributes are:

  • ID: This attribute stores a unique identifier for each Thread.

  • Name: This attribute store the name of Thread.

  • Priority: This attribute stores the priority of the Thread objects. Threads can have a priority between one and 10, where one is the lowest priority and 10 is the highest one. It's not recommended to change the priority of the threads, but it's a possibility that you can use if you want.

  • Status: This attribute stores the status of Thread. In Java, Thread can be in one of these six states: new, runnable, blocked, waiting, time waiting, or terminated.

In this recipe, we will develop a program that establishes the name and priority for 10 threads and then shows information about their status until they finish. The threads will calculate the multiplication table of a number.

Getting ready

The example of this recipe has been implemented using the Eclipse IDE. If you use Eclipse or other IDE such as NetBeans, open it and create a new Java project.

How to do it...

Follow these steps to implement the example:

  1. Create a class named Calculator and specify that it implements the Runnable interface.

    public class Calculator implements Runnable {
  2. Declare an int private attribute named number and implement the constructor of the class that initializes this attribute.

      private int number;
      public Calculator(int number) {
        this.number=number;
      }
  3. Implement the run() method. This method will execute the instructions of the thread that we are creating, so this method will calculate and print the multiplication table of a number.

      @Override
      public void run() {
        for (int i=1; i<=10; i++){
          System.out.printf("%s: %d * %d = %d\n",Thread.currentThread().getName(),number,i,i*number);
        }
      }
  4. Now, we implement the main class of this example. Create a class named Main and implement the main() method.

    public class Main {
      public static void main(String[] args) {
  5. Create an array of 10 threads and an array of 10 Thread.State to store the threads we are going to execute and their status.

        Thread threads[]=new Thread[10];
        Thread.State status[]=new Thread.State[10];
  6. Create 10 objects of the Calculator class, each initialized with a different number, and 10 threads to run them. Set the priority of five of them to the maximum value and set the priority of the rest to the minimum value.

        for (int i=0; i<10; i++){
          threads[i]=new Thread(new Calculator(i));
          if ((i%2)==0){
            threads[i].setPriority(Thread.MAX_PRIORITY);
          } else {
            threads[i].setPriority(Thread.MIN_PRIORITY);
          }
          threads[i].setName("Thread "+i);
        }
  7. Create a PrintWriter object to write to a file on the evolution of the status of the threads.

        try (FileWriter file = new FileWriter(".\\data\\log.txt");
    PrintWriter pw = new PrintWriter(file);){
  8. Write on this file the status of the 10 threads. Now, it becomes NEW.

          for (int i=0; i<10; i++){
    pw.println("Main : Status of Thread "+i+" : "  +             threads[i].getState());
            status[i]=threads[i].getState();
          }
  9. Start the execution of the 10 threads.

          for (int i=0; i<10; i++){
            threads[i].start();
          }
  10. Until the 10 threads end, we are going to check their status. If we detect a change in the status of a thread, we write them on the file.

          boolean finish=false;
          while (!finish) {
            for (int i=0; i<10; i++){
              if (threads[i].getState()!=status[i]) {
                writeThreadInfo(pw, threads[i],status[i]);
                status[i]=threads[i].getState();
              }
            }      
            finish=true;
            for (int i=0; i<10; i++){
    finish=finish &&(threads[i].getState()==State.TERMINATED);
            }
          }
  11. Implement the method writeThreadInfo() which writes the ID, name, priority, old status, and new status of Thread.

      private static void writeThreadInfo(PrintWriter pw, Thread thread, State state) {
    pw.printf("Main : Id %d - %s\n",thread.getId(),thread.getName());
    pw.printf("Main : Priority: %d\n",thread.getPriority());
    pw.printf("Main : Old State: %s\n",state);
    pw.printf("Main : New State: %s\n",thread.getState());
    pw.printf("Main : ************************************\n");
      }
  12. Run the example and open the log.txt file to see the evolution of the 10 threads.

How it works...

The following screenshot shows some lines of the log.txt file in an execution of this program. In this file, we can see that the threads with the highest priority end before the ones with the lowest priority. We also can see the evolution of the status of every thread.

The program shown in the console is the multiplication tables calculated by the threads and the evolution of the status of the different threads in the file log.txt. By this way, you can better see the evolution of the threads.

The class Thread has attributes to store all the information of a thread. The JVM uses the priority of the threads to select the one that uses the CPU at each moment and actualizes the status of every thread according to its situation.

If you don't specify a name for a thread, the JVM automatically assigns it one with the format, Thread-XX where XX is a number. You can't modify the ID or status of a thread. The Thread class doesn't implement the setId() and setStatus() methods to allow their modification.

There's more...

In this recipe, you learned how to access the information attributes using a Thread object. But you can also access these attributes from an implementation of the Runnable interface. You can use the static method currentThread() of the Thread class to access the Thread object that is running the Runnable object.

You have to take into account that the setPriority() method can throw an IllegalArgumentException exception if you try to establish a priority that isn't between one and 10.

See Also

  • The Interrupting a Thread recipe in Chapter 1, Thread Management

 

Interrupting a thread


A Java program with more than one execution thread only finishes when the execution of all of its threads end (more specifically, when all its non-daemon threads end its execution or when one of the threads use the System.exit() method). Sometimes, you will need to finish a thread, because you want to terminate a program, or when a user of the program wants to cancel the tasks that a Thread object is doing.

Java provides the interruption mechanism to indicate to a thread that we want to finish it. One peculiarity of this mechanism is that Thread has to check if it has been interrupted or not, and it can decide if it responds to the finalization request or not. Thread can ignore it and continue with its execution.

In this recipe, we will develop a program that creates Thread and, after 5 seconds, will force its finalization using the interruption mechanism.

Getting ready

The example of this recipe has been implemented using the Eclipse IDE. If you use Eclipse or other IDE such as NetBeans, open it and create a new Java project.

How to do it...

Follow these steps to implement the example:

  1. Create a class called PrimeGenerator that extends the Thread class.

    public class PrimeGenerator extends Thread{
  2. Override the run() method including a loop that will run indefinitely. In this loop, we are going to process consecutive numbers beginning at one. For each number, we will calculate if it's a prime number and, in that case, we are going to write it to the console.

      @Override
      public void run() {
        long number=1L;
        while (true) {
          if (isPrime(number)) {
            System.out.printf("Number %d is Prime",number);
          }
  3. After processing a number, check if the thread has been interrupted by calling the isInterrupted() method. If this method returns true, we write a message and end the execution of the thread.

          if (isInterrupted()) {
            System.out.printf("The Prime Generator has been Interrupted");
            return;
          }
          number++;
        }
      }
  4. Implement the isPrime() method. It returns a boolean value indicating if the number that is received as a parameter is a prime number (true) or not (false).

      private boolean isPrime(long number) {
        if (number <=2) {
          return true;
        }
        for (long i=2; i<number; i++){
          if ((number % i)==0) {
            return false;
          }
        }
        return true;
      }
  5. Now, implement the main class of the example by implementing a class called Main and implementing the main() method.

    public class Main {
      public static void main(String[] args) {
  6. Create and start an object of the PrimeGenerator class.

        Thread task=new PrimeGenerator();
        task.start();
  7. Wait for 5 seconds and interrupt the PrimeGenerator thread.

        try {
          Thread.sleep(5000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
    task.interrupt();
  8. Run the example and see the results.

How it works...

The following screenshot shows the result of execution of the previous example. We can see how the PrimeGenerator thread writes the message and ends its execution when it detects that it has been interrupted. Refer to the following screenshot:

The Thread class has an attribute that stores a boolean value indicating whether the thread has been interrupted or not. When you call the interrupt() method of a thread, you set that attribute to true. The isInterrupted() method only returns the value of that attribute.

There's more...

The Thread class has another method to check whether Thread has been interrupted or not. It's the static method, interrupted(), that checks whether the current executing thread has been interrupted or not.

Note

There is an important difference between the isInterrupted() and the interrupted() methods. The first one doesn't change the value of the interrupted attribute, but the second one sets it to false. As the interrupted() method is a static method, the utilization of the isInterrupted() method is recommended.

As I mentioned earlier, Thread can ignore its interruption, but this is not the expected behaviour.

 

Controlling the interruption of a thread


In the previous recipe, you learned how you can interrupt the execution of a thread and what you have to do to control this interruption in the Thread object. The mechanism shown in the previous example can be used if the thread that can be interrupted is simple. But if the thread implements a complex algorithm divided into some methods, or it has methods with recursive calls, we can use a better mechanism to control the interruption of the thread. Java provides the InterruptedException exception for this purpose. You can throw this exception when you detect the interruption of the thread and catch it in the run() method.

In this recipe, we will implement Thread that looks for files with a determined name in a folder and in all its subfolders to show how to use the InterruptedException exception to control the interruption of a thread.

Getting ready

The example of this recipe has been implemented using the Eclipse IDE. If you use Eclipse or other IDE such as NetBeans, open it and create a new Java project.

How to do it...

Follow these steps to implement the example:

  1. Create a class called FileSearch and specify that it implements the Runnable interface.

    public class FileSearch implements Runnable {
  2. Declare two private attributes, one for the name of the file we are going to search for and one for the initial folder. Implement the constructor of the class, which initializes these attributes.

      private String initPath;
      private String fileName;
      public FileSearch(String initPath, String fileName) {
        this.initPath = initPath;
        this.fileName = fileName;
      }
  3. Implement the run() method of the FileSearch class. It checks if the attribute fileName is a directory and, if it is, calls the method processDirectory(). This method can throw an InterruptedException exception, so we have to catch them.

      @Override
      public void run() {
        File file = new File(initPath);
        if (file.isDirectory()) {
          try {
            directoryProcess(file);
          } catch (InterruptedException e) {
            System.out.printf("%s: The search has been interrupted",Thread.currentThread().getName());
          }
        }
      }
  4. Implement the directoryProcess() method. This method will obtain the files and subfolders in a folder and process them. For each directory, the method will make a recursive call passing the directory as a parameter. For each file, the method will call the fileProcess() method. After processing all files and folders, the method checks if Thread has been interrupted and, in this case, throws an InterruptedException exception.

      private void directoryProcess(File file) throws InterruptedException {
        File list[] = file.listFiles();
        if (list != null) {
          for (int i = 0; i < list.length; i++) {
            if (list[i].isDirectory()) {
              directoryProcess(list[i]);
            } else {
              fileProcess(list[i]);
            }
          }
        }
        if (Thread.interrupted()) {
          throw new InterruptedException();
        }
      }
  5. Implement the processFile() method. This method will compare the name of the file it's processing with the name we are searching for. If the names are equal, we will write a message in the console. After this comparison, Thread will check if it has been interrupted and, in this case, it throws an InterruptedException exception.

      private void fileProcess(File file) throws InterruptedException {
        if (file.getName().equals(fileName)) {
          System.out.printf("%s : %s\n",Thread.currentThread().getName() ,file.getAbsolutePath());
        }
        if (Thread.interrupted()) {
          throw new InterruptedException();
        }
      }
  6. Now, let's implement the main class of the example. Implement a class called Main that contains the main() method.

    public class Main {
      public static void main(String[] args) {
  7. Create and initialize an object of the FileSearch class and Thread to execute its task. Then, start executing Thread.

        FileSearch searcher=new FileSearch("C:\\","autoexec.bat");
        Thread thread=new Thread(searcher);
        thread.start();
  8. Wait for 10 seconds and interrupt Thread.

        try {
          TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        thread.interrupt();
      }
  9. Run the example and see the results.

How it works...

The following screenshot shows the result of an execution of this example. You can see how the FileSearch object ends its execution when it detects that it has been interrupted. Refer to the following screenshot:

In this example, we use Java exceptions to control the interruption of Thread. When you run the example, the program starts going through folders by checking if they have the file or not. For example, if you enter in the folder \b\c\d, the program will have three recursive calls to the processDirectory() method. When it detects that it has been interrupted, it throws an InterruptedException exception and continues the execution in the run() method, no matter how many recursive calls have been made.

There's more...

The InterruptedException exception is thrown by some Java methods related with the concurrency API such as sleep().

See also

  • The Interrupting a thread recipe in Chapter 1, Thread Management

 

Sleeping and resuming a thread


Sometimes, you'll be interested in interrupting the execution of Thread during a determined period of time. For example, a thread in a program checks a sensor state once per minute. The rest of the time, the thread does nothing. During this time, the thread doesn't use any resources of the computer. After this time, the thread will be ready to continue with its execution when the JVM chooses it to be executed. You can use the sleep() method of the Thread class for this purpose. This method receives an integer as the parameter indicates the number of milliseconds that the thread suspends its execution. When the sleeping time ends, the thread continues with its execution in the instruction, after the sleep() method calls, when the JVM assigns them CPU time.

Another possibility is to use the sleep() method of an element of the TimeUnit enumeration. This method uses the sleep() method of the Thread class to put the current thread to sleep, but it receives the parameter in the unit that it represents and converts it to milliseconds.

In this recipe, we will develop a program that uses the sleep() method to write the actual date every second.

Getting ready

The example of this recipe has been implemented using the Eclipse IDE. If you use Eclipse or other IDE such as NetBeans, open it and create a new Java project.

How to do it...

Follow these steps to implement the example:

  1. Create a class called FileClock and specify that it implements the Runnable interface.

    public class FileClock implements Runnable {
  2. Implement the run() method.

      @Override
      public void run() {
  3. Write a loop with 10 iterations. In each iteration, create a Date object, write it to the file, and call the sleep() method of the SECONDS attribute of the TimeUnit class to suspend the execution of the thread for one second. With this value, the thread will be sleeping for approximately one second. As the sleep() method can throw an InterruptedException exception, we have to include the code to catch it. It's a good practice to include code that frees or closes the resources the thread is using when it's interrupted.

        for (int i = 0; i < 10; i++) {
          System.out.printf("%s\n", new Date());
          try {
            TimeUnit.SECONDS.sleep(1);
          } catch (InterruptedException e) {
            System.out.printf("The FileClock has been interrupted");
          }
        }
      }
  4. We have implemented the thread. Now, let's implement the main class of the example. Create a class called FileMain that contains the main() method.

    public class FileMain {
      public static void main(String[] args) {
  5. Create an object of the FileClock class and a thread to execute it. Then, start executing Thread.

        FileClock clock=new FileClock();
        Thread thread=new Thread(clock);
        thread.start();
  6. Call the sleep() method of the SECONDS attribute of the TimeUnit class in the main Thread to wait for 5 seconds.

        try {
          TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
          e.printStackTrace();
        };
  7. Interrupt the FileClock thread.

        thread.interrupt();
  8. Run the example and see the results.

How it works...

When you run the example, you can see how the program writes a Date object per second and then, the message indicating that the FileClock thread has been interrupted.

When you call the sleep() method, Thread leaves the CPU and stops its execution for a period of time. During this time, it's not consuming CPU time, so the CPU can be executing other tasks.

When Thread is sleeping and is interrupted, the method throws an InterruptedException exception immediately and doesn't wait until the sleeping time finishes.

There's more...

The Java concurrency API has another method that makes a Thread object leave the CPU. It's the yield() method, which indicates to the JVM that the Thread object can leave the CPU for other tasks. The JVM does not guarantee that it will comply with this request. Normally, it's only used for debug purposes.

 

Waiting for the finalization of a thread


In some situations, we will have to wait for the finalization of a thread. For example, we may have a program that will begin initializing the resources it needs before proceeding with the rest of the execution. We can run the initialization tasks as threads and wait for its finalization before continuing with the rest of the program.

For this purpose, we can use the join() method of the Thread class. When we call this method using a thread object, it suspends the execution of the calling thread until the object called finishes its execution.

In this recipe, we will learn the use of this method with the initialization example.

Getting ready

The example of this recipe has been implemented using the Eclipse IDE. If you use Eclipse or other IDE such as NetBeans, open it and create a new Java project.

How to do it...

Follow these steps to implement the example:

  1. Create a class called DataSourcesLoader and specify that it implements the Runnable interface.

    public class DataSourcesLoader implements Runnable {
  2. Implement the run() method. It writes a message to indicate that it starts its execution, sleeps for 4 seconds, and writes another message to indicate that it ends its execution.

      @Override
      public void run() {
        System.out.printf("Beginning data sources loading: %s\n",new Date());
        try {
          TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        System.out.printf("Data sources loading has finished: %s\n",new Date());
      }
  3. Create a class called NetworkConnectionsLoader and specify that it implements the Runnable interface. Implement the run() method. It will be equal to the run() method of the DataSourcesLoader class, but this will sleep for 6 seconds.

  4. Now, create a class called Main that contains the main() method.

    public class Main {
      public static void main(String[] args) {
  5. Create an object of the DataSourcesLoader class and Thread to run it.

        DataSourcesLoader dsLoader = new DataSourcesLoader();
        Thread thread1 = new Thread(dsLoader,"DataSourceThread");
  6. Create an object of the NetworkConnectionsLoader class and Thread to run it.

        NetworkConnectionsLoader ncLoader = new NetworkConnectionsLoader();
        Thread thread2 = new Thread(ncLoader,"NetworkConnectionLoader");
  7. Call the start() method of both the Thread objects.

        thread1.start();
        thread2.start(); 
  8. Wait for the finalization of both threads using the join() method. This method can throw an InterruptedException exception, so we have to include the code to catch it.

        try {
          thread1.join();
          thread2.join();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
  9. Write a message to indicate the end of the program.

        System.out.printf("Main: Configuration has been loaded: %s\n",new Date());
  10. Run the program and see the results.

How it works...

When you run this program, you can see how both Thread objects start their execution. First, the DataSourcesLoader thread finishes its execution. Then, the NetworkConnectionsLoader class finishes its execution and, at that moment, the main Thread object continues its execution and writes the final message.

There's more...

Java provides two additional forms of the join() method:

  • join (long milliseconds)

  • join (long milliseconds, long nanos)

In the first version of the join() method, instead of waiting indefinitely for the finalization of the thread called, the calling thread waits for the milliseconds specified as a parameter of the method. For example, if the object thread1 has the code, thread2.join(1000), the thread thread1 suspends its execution until one of these two conditions is true:

  • thread2 finishes its execution

  • 1000 milliseconds have been passed

When one of these two conditions is true, the join() method returns.

The second version of the join() method is similar to the first one, but receives the number of milliseconds and the number of nanoseconds as parameters.

 

Creating and running a daemon thread


Java has a special kind of thread called daemon thread. These kind of threads have very low priority and normally only executes when no other thread of the same program is running. When daemon threads are the only threads running in a program, the JVM ends the program finishing these threads.

With these characteristics, the 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 the thread. They can't do important jobs because we don't know when they are going to have CPU time and they can finish any time if there aren't any other threads running. A typical example of these kind of threads is the Java garbage collector.

In this recipe, we will learn how to create a daemon thread developing an example with two threads; one user thread that writes events on a queue and a daemon one that cleans that queue, removing the events which were generated more than 10 seconds ago.

Getting ready

The example of this recipe has been implemented using the Eclipse IDE. If you use Eclipse or other IDE such as NetBeans, open it and create a new Java project.

How to do it...

Follow these steps to implement the example:

  1. Create the Event class. This class only stores information about the events our program will work with. Declare two private attributes, one called date of java.util.Date type and the other called event of String type. Generate the methods to write and read their values.

  2. Create the WriterTask class and specify that it implements the Runnable interface.

    public class WriterTask implements Runnable {
  3. Declare the queue that stores the events and implement the constructor of the class, which initializes this queue.

    private Deque<Event> deque;
      public WriterTask (Deque<Event> deque){
        this.deque=deque;
      }
  4. Implement the 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 one 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();
          }
        }
      }
  5. Create the CleanerTask class and specify that it extends the Thread class.

    public class CleanerTask extends Thread {
  6. Declare the queue that stores the events and implement the constructor of the class, which initializes this queue. In the constructor, mark this Thread as a daemon thread with the setDaemon() method.

      private Deque<Event> deque;
      public CleanerTask(Deque<Event> deque) {
        this.deque = deque;
        setDaemon(true);
      }
  7. Implement the 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);
        }
      }
  8. Implement the 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());
        }
      }
  9. Now, implement the main class. Create a class called Main with a main() method.

    public class Main {
      public static void main(String[] args) {
  10. Create the queue to store the events using the Deque class.

        Deque<Event> deque=new ArrayDeque<Event>();
  11. Create and start three WriterTask threads and one CleanerTask.

        WriterTask writer=new WriterTask(deque);
        for (int i=0; i<3; i++){
          Thread thread=new Thread(writer);
          thread.start();
        }
        CleanerTask cleaner=new CleanerTask(deque);
        cleaner.start();
  12. Run the program and see the results.

How it works...

If you analyze the output of one execution of the program, you can see how the queue begins to grow until it has 30 events and then, its size will vary between 27 and 30 events until the end of the execution.

The program starts with three WriterTask threads. Each Thread writes an event and sleeps for one second. After the first 10 seconds, we have 30 threads in the queue. During these 10 seconds, CleanerTasks has been executing while the three WriterTask threads were sleeping, but it hasn't deleted any event, because all of them were generated less than 10 seconds ago. During the rest of the execution, CleanerTask deletes three events every second and the three WriterTask threads write another three, so the size of the queue varies between 27 and 30 events.

You can play with the 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.

There's more...

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.

You can use the isDaemon() method to check if a thread is a daemon thread (the method returns true) or a user thread (the method returns false).

 

Processing uncontrolled exceptions in a thread


There are two kinds of exceptions in Java:

  • Checked exceptions: These exceptions must be specified in the throws clause of a method or caught inside them. For example, IOException or ClassNotFoundException.

  • Unchecked exceptions: These exceptions don't have to be specified or caught. For example, NumberFormatException.

When a checked exception is thrown inside the run() method of a Thread object, we have to catch and treat them, because the run() method doesn't accept a throws clause. When an unchecked exception is thrown inside the run() method of a Thread object, the default behaviour is to write the stack trace in the console and exit the program.

Fortunately, Java provides us with a mechanism to catch and treat the unchecked exceptions thrown in a Thread object to avoid the program ending.

In this recipe, we will learn this mechanism using an example.

Getting ready

The example of this recipe has been implemented using the Eclipse IDE. If you use Eclipse or other IDE such as NetBeans, open it and create a new Java project.

How to do it...

Follow these steps to implement the example:

  1. First of all, we have to implement a class to treat the unchecked exceptions. This class must implement the UncaughtExceptionHandler interface and implement the uncaughtException() method declared in that interface. In our case, call this class ExceptionHandler and make the method to write information about Exception and Thread that threw it. Following is the code:

    public class ExceptionHandler implements UncaughtExceptionHandler {
      public void uncaughtException(Thread t, Throwable e) {
        System.out.printf("An exception has been captured\n");
        System.out.printf("Thread: %s\n",t.getId());
        System.out.printf("Exception: %s: %s\n",e.getClass().getName(),e.getMessage());
        System.out.printf("Stack Trace: \n");
        e.printStackTrace(System.out);
        System.out.printf("Thread status: %s\n",t.getState());
      }
    }
  2. Now, implement a class that throws an unchecked exception. Call this class Task, specify that it implements the Runnable interface, implement the run() method, and force the exception, for example, try to convert a string value into an int value.

    public class Task implements Runnable {
      @Override
      public void run() {
        int numero=Integer.parseInt("TTT");
      }
    }
  3. Now, implement the main class of the example. Implement a class called Main with a main() method.

    public class Main {
      public static void main(String[] args) {
  4. Create a Task object and Thread to run it. Set the unchecked exception handler using the setUncaughtExceptionHandler() method and start executing Thread.

        Task task=new Task();
        Thread thread=new Thread(task);
        thread.setUncaughtExceptionHandler(new ExceptionHandler());
        thread.start();
        }
    }
  5. Run the example and see the results.

How it works...

In the following screenshot, you can see the results of the execution of the example. The exception is thrown and captured by the handler that writes the information in console about Exception and Thread that threw it. Refer to the following screenshot:

When an exception is thrown in a thread and is not caught (it has to be an unchecked exception), the JVM checks if the thread has an uncaught exception handler set by the corresponding method. If it has, the JVM invokes this method with the Thread object and Exception as arguments.

If the thread has not got an uncaught exception handler, the JVM prints the stack trace in the console and exits the program.

There's more...

The Thread class has another method related to the process of uncaught exceptions. It's the static method setDefaultUncaughtExceptionHandler() that establishes an exception handler for all the Thread objects in the application.

When an uncaught exception is thrown in Thread, the JVM looks for three possible handlers for this exception.

First, it looks for the uncaught exception handler of the Thread objects as we learned in this recipe. If this handler doesn't exist, then the JVM looks for the uncaught exception handler for ThreadGroup of the Thread objects as was explained in the Processing uncontrolled exceptions in a group of threads recipe. If this method doesn't exist, the JVM looks for the default uncaught exception handler as we learned in this recipe.

If none of the handlers exits, the JVM writes the stack trace of the exception in the console and exits the program.

See also

  • The Processing uncontrolled exceptions in a group of threads recipe in Chapter 1, Thread Management

 

Using local thread variables


One of the most critical aspects of a concurrent application is shared data. This has special importance in those objects that extend the Thread class or implement the Runnable interface.

If you create an object of a class that implements the Runnable interface and then start various Thread objects using the same Runnable object, all the threads share the same attributes. This means that, if you change an attribute in a thread, all the threads will be affected by this change.

Sometimes, you will be interested in having an attribute that won't be shared between all the threads that run the same object. The Java Concurrency API provides a clean mechanism called thread-local variables with a very good performance.

In this recipe, we will develop a program that has the problem exposed in the first paragraph and another program that solves this problem using the thread-local variables mechanism.

Getting ready

The example of this recipe has been implemented using the Eclipse IDE. If you use Eclipse or other IDE such as NetBeans, open it and create a new Java project.

How to do it...

Follow these steps to implement the example:

  1. First, we are going to implement a program that has the problem exposed previously. Create a class called UnsafeTask and specify that it implements the Runnable interface. Declare a private java.util.Date attribute.

    public class UnsafeTask implements Runnable{
      private Date startDate;
  2. Implement the run() method of the UnsafeTask object. This method will initialize the startDate attribute, write its value to the console, sleep for a random period of time, and again write the value of the startDate attribute.

      @Override
      public void run() {
        startDate=new Date();
        System.out.printf("Starting Thread: %s : %s\n",Thread.currentThread().getId(),startDate);
        try {
          TimeUnit.SECONDS.sleep( (int)Math.rint(Math.random()*10));
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        System.out.printf("Thread Finished: %s : %s\n",Thread.currentThread().getId(),startDate);
      }
  3. Now, let's implement the main class of this problematic application. Create a class called Main with a main() method. This method will create an object of the UnsafeTask class and start three threads using that object, sleeping for 2 seconds between each thread.

    public class Core {
      public static void main(String[] args) {
        UnsafeTask task=new UnsafeTask();
        for (int i=0; i<10; i++){
          Thread thread=new Thread(task);
          thread.start();
          try {
            TimeUnit.SECONDS.sleep(2);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }
  4. In the following screenshot, you can see the results of this program's execution. Each Thread has a different start time but, when they finish, all have the same value in its startDate attribute.

  5. As mentioned earlier, we are going to use the thread-local variables mechanism to solve this problem.

  6. Create a class called SafeTask and specify that it implements the Runnable interface.

    public class SafeTask implements Runnable {
  7. Declare an object of the ThreadLocal<Date> class. This object will have an implicit implementation that includes the method initialValue(). This method will return the actual date.

      private static ThreadLocal<Date> startDate= new ThreadLocal<Date>() {
        protected Date initialValue(){
          return new Date();
        }
      };
  8. Implement the run() method. It has the same functionality as the run() method of UnsafeClass, but it changes the way to access to the startDate attribute.

      @Override
      public void run() {
        System.out.printf("Starting Thread: %s : %s\n",Thread.currentThread().getId(),startDate.get());
        try {
          TimeUnit.SECONDS.sleep((int)Math.rint(Math.random()*10));
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        System.out.printf("Thread Finished: %s : %s\n",Thread.currentThread().getId(),startDate.get());
      }
  9. The main class of this example is the same as the unsafe example, changing the name of the Runnable class.

  10. Run the example and analyze the difference.

How it works...

In the following screenshot, you can see the results of the execution of the safe sample. Now, the three Thread objects have their own value of the startDate attribute. Refer to the following screenshot:

Thread-local variables store a value of an attribute for each Thread that uses one of these variables. You can read the value using the get() method and change the value using the set() method. The first time you access the value of a thread-local variable, if it has no value for the Thread object that it is calling, the thread-local variable calls the initialValue() method to assign a value for that Thread and returns the initial value.

There's more...

The thread-local class also provides the remove() method that deletes the value stored in the thread-local variable for the thread that it's calling.

The Java Concurrency API includes the InheritableThreadLocal class that provides inheritance of values for threads created from a thread. If a thread A has a value in a thread-local variable and it creates another thread B, the thread B will have the same value as the thread A in the thread-local variable. You can override the childValue() method that is called to initialize the value of the child thread in the thread-local variable. It receives the value of the parent thread in the thread-local variable as a parameter.

 

Grouping threads into a group


An interesting functionality offered by the concurrency API of Java is the ability to group the threads. This allows us to treat the threads of a group as a single unit and provides access to the Thread objects that belong to a group to do an operation with them. For example, you have some threads doing the same task and you want to control them, irrespective of how many threads are still running, the status of each one will interrupt all of them with a single call.

Java provides the ThreadGroup class to work with groups of threads. A ThreadGroup object can be formed by Thread objects and by another ThreadGroup object, generating a tree structure of threads.

In this recipe, we will learn to work with ThreadGroup objects developing a simple example. We will have 10 threads sleeping during a random period of time (simulating a search, for example) and, when one of them finishes, we are going to interrupt the rest.

Getting ready

The example of this recipe has been implemented using the Eclipse IDE. If you use Eclipse or other IDE such as NetBeans, open it and create a new Java project.

How to do it...

Follow these steps to implement the example:

  1. First, create a class called Result. It will store the name of Thread that finishes first. Declare a private String attribute called name and the methods to read and set the value.

  2. Create a class called SearchTask and specify that it implements the Runnable interface.

    public class SearchTask implements Runnable {
  3. Declare a private attribute of the Result class and implement the constructor of the class that initializes this attribute.

      private Result result;
      public SearchTask(Result result) {
        this.result=result;
      }
  4. Implement the run() method. It will call the doTask() method and wait for it to finish or for a InterruptedException exception. The method will write messages to indicate the start, end, or interruption of this Thread.

      @Override
      public void run() {
        String name=Thread.currentThread().getName();
        System.out.printf("Thread %s: Start\n",name);
        try {
          doTask();
          result.setName(name);
        } catch (InterruptedException e) {
          System.out.printf("Thread %s: Interrupted\n",name);
          return;
        }
        System.out.printf("Thread %s: End\n",name);
      }
  5. Implement the doTask() method. It will create a Random object to generate a random number and call the sleep() method with that random number.

      private void doTask() throws InterruptedException {
        Random random=new Random((new Date()).getTime());
        int value=(int)(random.nextDouble()*100);
        System.out.printf("Thread %s: %d\n",Thread.currentThread().getName(),value);
        TimeUnit.SECONDS.sleep(value);
      }
  6. Now, create the main class of the example by creating a class called Main and implement the main() method.

    public class Main {
      public static void main(String[] args) {
  7. First, create a ThreadGroup object and call them Searcher.

        ThreadGroup threadGroup = new ThreadGroup("Searcher");
  8. Then, create a SearchTask object and a Result object.

        Result result=new Result();
    SearchTask searchTask=new SearchTask(result);
  9. Now, create 10 Thread objects using the SearchTask object. When you call the constructor of the Thread class, pass it as the first argument of the ThreadGroup object.

        for (int i=0; i<5; i++) {
          Thread thread=new Thread(threadGroup, searchTask);
          thread.start();
          try {
            TimeUnit.SECONDS.sleep(1);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
  10. Write information about the ThreadGroup object using the list() method.

        System.out.printf("Number of Threads: %d\n",threadGroup.activeCount());
        System.out.printf("Information about the Thread Group\n");
        threadGroup.list();
  11. Use the activeCount() and enumerate() methods to know how many Thread objects are associated with the ThreadGroup objects and get a list of them. We can use this method to get, for example, the state of each Thread.

        Thread[] threads=new Thread[threadGroup.activeCount()];
        threadGroup.enumerate(threads);
        for (int i=0; i<threadGroup.activeCount(); i++) {
          System.out.printf("Thread %s: %s\n",threads[i].getName(),threads[i].getState());
        }
  12. Call the method waitFinish() . We will implement this method later. It will wait until one of the threads of the ThreadGroup objects ends.

        waitFinish(threadGroup);
  13. Interrupt the rest of the threads of the group using the interrupt() method.

        threadGroup.interrupt();
  14. Implement the waitFinish() method. It will use the activeCount() method to control the end of one of the threads.

      private static void waitFinish(ThreadGroup threadGroup) {
        while (threadGroup.activeCount()>9) {
          try {
            TimeUnit.SECONDS.sleep(1);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
  15. Run the example and see the results.

How it works...

In the following screenshot, you can see the output of the list() method and the output generated when we write the status of each Thread object, as shown in the following screenshot:

The ThreadGroup class stores the Thread objects and the other ThreadGroup objects associated with it, so it can access all of their information (status, for example) and perform operations over all its members (interrupt, for example).

There's more...

The ThreadGroup class has more methods. Check the API documentation to have a complete explanation of all of these methods.

 

Processing uncontrolled exceptions in a group of threads


A very important aspect in every programming language is the mechanism that provides management of error situations in your application. Java language, as almost all modern programming languages, implements an exception-based mechanism to manage error situations. It provides a lot of classes to represent different errors. Those exceptions are thrown by the Java classes when an error situation is detected. You can also use those exceptions, or implement your own exceptions, to manage the errors produced in your classes.

Java also provides a mechanism to capture and process those exceptions. There are exceptions that must be captured or re-thrown using the throws clause of a method. These exceptions are called checked exceptions. There are exceptions that don't have to be specified or caught. These are the unchecked exceptions.

In the recipe, Controlling the interruption of a Thread, you learned how to use a generic method to process all the uncaught exceptions that are thrown in a Thread object.

Another possibility is to establish a method that captures all the uncaught exceptions thrown by any Thread of the ThreadGroup class.

In this recipe, we will learn to set this handler using an example.

Getting ready

The example of this recipe has been implemented using the Eclipse IDE. If you use Eclipse or other IDE such as NetBeans, open it and create a new Java project.

How to do it...

Follow these steps to implement the example:

  1. First, we have to extend the ThreadGroup class by creating a class called MyThreadGroup that extends from ThreadGroup. We have to declare a constructor with one parameter, because the ThreadGroup class doesn't have a constructor without it.

    public class MyThreadGroup extends ThreadGroup {
      public MyThreadGroup(String name) {
        super(name);
      }
  2. Override the uncaughtException() method. This method is called when an exception is thrown in one of the threads of the ThreadGroup class. In this case, this method will write in the console information about the exception and Thread that throws it and interrupts the rest of the threads in the ThreadGroup class.

      @Override
      public void uncaughtException(Thread t, Throwable e) {
        System.out.printf("The thread %s has thrown an Exception\n",t.getId());
        e.printStackTrace(System.out);
        System.out.printf("Terminating the rest of the Threads\n");
        interrupt();
      }
  3. Create a class called Task and specify that it implements the Runnable interface.

    public class Task implements Runnable {
  4. Implement the run() method. In this case, we will provoke an AritmethicException exception. For this, we will divide 1000 between random numbers until the random generator generates a zero and the exception is thrown.

      @Override
      public void run() {
        int result;
        Random random=new Random(Thread.currentThread().getId());
        while (true) {
          result=1000/((int)(random.nextDouble()*1000));
          System.out.printf("%s : %f\n",Thread.currentThread().getId(),result);
          if (Thread.currentThread().isInterrupted()) {
            System.out.printf("%d : Interrupted\n",Thread.currentThread().getId());
            return;
          }
        }
      }
  5. Now, we are going to implement the main class of the example by creating a class called Main and implement the main() method.

    public class Main {
      public static void main(String[] args) {
  6. Create an object of the MyThreadGroup class.

        MyThreadGroup threadGroup=new MyThreadGroup("MyThreadGroup");
  7. Create an object of the Task class.

        Task task=new Task();
  8. Create two Thread objects with this Task and start them.

        for (int i=0; i<2; i++){
          Thread t=new Thread(threadGroup,task);
          t.start();
        }
  9. Run the example and see the results.

How it works...

When you run the example, you will see how one of the Thread objects threw the exception and the other one was interrupted.

When an uncaught exception is thrown in Thread, the JVM looks for three possible handlers for this exception.

First, it looks for the uncaught exception handler of the thread, as was explained in the Processing uncontrolled exceptions in a Thread recipe. If this handler doesn't exist, then the JVM looks for the uncaught exception handler for the ThreadGroup class of the thread, as we learned in this recipe. If this method doesn't exist, the JVM looks for the default uncaught exception handler, as was explained in the Processing uncontrolled exceptions in a Thread recipe.

If none of the handlers exit, the JVM writes the stack trace of the exception in the console and exits the program.

See also

  • The Processing uncontrolled exceptions in a thread recipe in Chapter 1, Thread Management

 

Creating threads through a factory


The factory pattern is one of the most used design patterns in the object-oriented programming world. It is a creational pattern and its objective is to develop an object whose mission will be creating other objects of one or several classes. Then, when we want to create an object of one of those classes, we use the factory instead of using the new operator.

With this factory, we centralize the creation of objects with some advantages:

  • It's easy to change the class of the objects created or the way we create these objects.

  • It's easy to limit the creation of objects for limited resources. For example, we can only have n objects of a type.

  • It's easy to generate statistical data about the creation of the objects.

Java provides an interface, the ThreadFactory interface to implement a Thread object factory. Some advanced utilities of the Java concurrency API use thread factories to create threads.

In this recipe, we will learn how to implement a ThreadFactory interface to create Thread objects with a personalized name while we save statistics of the Thread objects created.

Getting ready

The example of this recipe has been implemented using the Eclipse IDE. If you use Eclipse or other IDE such as NetBeans, open it and create a new Java project.

How to do it...

Follow these steps to implement the example:

  1. Create a class called MyThreadFactory and specify that it implements the ThreadFactory interface.

    public class MyThreadFactory implements ThreadFactory {
  2. Declare three attributes: an integer number called counter, which we will use to store the number of the Thread object created, a String called name with the base name of every Thread created, and a List of String objects called stats to save statistical data about the Thread objects created. We also implement the constructor of the class that initializes these attributes.

      private int counter;
      private String name;
      private List<String> stats;
      
      public MyThreadFactory(String name){
        counter=0;
        this.name=name;
        stats=new ArrayList<String>();
      }
  3. Implement the newThread() method. This method will receive a Runnable interface and returns a Thread object for this Runnable interface. In our case, we generate the name of the Thread object, create the new Thread object, and save the statistics.

      @Override
      public Thread newThread(Runnable r) {
        Thread t=new Thread(r,name+"-Thread_"+counter);
        counter++;
        stats.add(String.format("Created thread %d with name %s on %s\n",t.getId(),t.getName(),new Date()));
        return t;
      }
  4. Implement the method getStatistics() that returns a String object with the statistical data of all the Thread objects created.

      public String getStats(){
        StringBuffer buffer=new StringBuffer();
        Iterator<String> it=stats.iterator();
        
        while (it.hasNext()) {
          buffer.append(it.next());
          buffer.append("\n");
        }
        
        return buffer.toString();
      }
  5. Create a class called Task and specify that it implements the Runnable interface. For this example, these tasks are going to do nothing apart from sleeping for one second.

    public class Task implements Runnable {
      @Override
      public void run() {
        try {
          TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  6. Create the main class of the example. Create a class called Main and implement the main() method.

    public class Main {
      public static void main(String[] args) {
  7. Create a MyThreadFactory object and a Task object.

        MyThreadFactory factory=new MyThreadFactory("MyThreadFactory");
        Task task=new Task();
  8. Create 10 Thread objects using the MyThreadFactory object and start them.

        Thread thread;
        System.out.printf("Starting the Threads\n");
        for (int i=0; i<10; i++){
          thread=factory.newThread(task);
          thread.start();
        }
  9. Write in the console the statistics of the thread factory.

        System.out.printf("Factory stats:\n");
        System.out.printf("%s\n",factory.getStats());
  10. Run the example and see the results.

How it works...

The ThreadFactory interface has only one method called newThread. It receives a Runnable object as a parameter and returns a Thread object. When you implement a ThreadFactory interface, you have to implement that interface and override this method. Most basic ThreadFactory, has only one line.

return new Thread(r);

You can improve this implementation by adding some variants by:

  • Creating personalized threads, as in the example, using a special format for the name or even creating our own thread class that inherits the Java Thread class

  • Saving thread creation statistics, as shown in the previous example

  • Limiting the number of threads created

  • Validating the creation of the threads

  • And anything more you can imagine

The use of the factory design pattern is a good programming practice but, if you implement a ThreadFactory interface to centralize the creation of threads, you have to review the code to guarantee that all threads are created using that factory.

See also

  • The Implementing the ThreadFactory interface to generate custom threads recipe in Chapter 7, Customizing Concurrency Classes

  • The Using our ThreadFactory in an Executor object recipe in Chapter 7, Customizing Concurrency Classes

About the Author

  • Javier Fernández González

    Javier Fernández González is a software architect with almost 15 years experience in Java technologies. He has worked as a teacher, researcher, programmer, analyst, and writer, and he now works as an architect in all types of projects related to Java, especially J2EE. As a teacher has over 1,000 hours of training in basic Java, J2EE, and the Struts framework.

    As a researcher, he has worked in the field of information retrieval, developing applications for processing large amounts of data in Java, and has participated as a co-author in several journal articles and conference presentations.

    Recently, he worked on developing J2EE web applications for various clients from different sectors (public administration, insurance, healthcare, transportation, and so on). He has also worked as a software architect. He is the author of the books, Java 7 Concurrency Cookbook and Mastering Concurrency Programming with Java 8 by Packt Publishing.

    Browse publications by this author
Book Title
Access this book and the full library for FREE
Access now