Book Image

Java 9 Concurrency Cookbook, Second Edition - Second Edition

By : Javier Fernández González
Book Image

Java 9 Concurrency Cookbook, Second Edition - Second Edition

By: Javier Fernández González

Overview of this book

Writing concurrent and parallel programming applications is an integral skill for any Java programmer. Java 9 comes with a host of fantastic features, including significant performance improvements and new APIs. This book will take you through all the new APIs, showing you how to build parallel and multi-threaded applications. The book covers all the elements of the Java Concurrency API, with essential recipes that will help you take advantage of the exciting new capabilities. You will learn how to use parallel and reactive streams to process massive data sets. Next, you will move on to create streams and use all their intermediate and terminal operations to process big collections of data in a parallel and functional way. Further, you’ll discover a whole range of recipes for almost everything, such as thread management, synchronization, executors, parallel and reactive streams, and many more. At the end of the book, you will learn how to obtain information about the status of some of the most useful components of the Java Concurrency API and how to test concurrent applications using different tools.
Table of Contents (12 chapters)

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 should be this: creating other objects of one or several classes. With this, if you want to create an object of one of these classes, you could just use the factory instead of using a 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 you'd create them.
  • It's easy to limit the creation of objects for limited resources; for example, we can only have n objects of a given type.
  • It's easy to generate statistical data about the creation of 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, you will learn how to implement a ThreadFactory interface to create thread objects with a personalized name while saving the statistics of the thread objects created.

Getting ready

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.

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 {
  1. Declare three attributes: an integer number called counter, which we will use to store the number of thread objects 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. 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>();
}
  1. Implement the newThread() method. This method will receive a Runnable interface and return 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;
}
  1. Implement the getStatistics() method; it 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();
}
  1. Create a class called Task and specify that it implements the Runnable interface. In this example, these tasks are going to do nothing apart from sleeping for 1 second:
        public class Task implements Runnable { 
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
  1. 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) {
  1. Create a MyThreadFactory object and a Task object:
        MyThreadFactory factory=new MyThreadFactory("MyThreadFactory"); 
Task task=new Task();
  1. 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();
}
  1. Write the statistics of the thread factory in the console:
        System.out.printf("Factory stats:\n"); 
System.out.printf("%s\n",factory.getStats());
  1. 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 it and override the newThread method. The most basic ThreadFactory has only one line:

    return new Thread(r);

You can improve this implementation by adding some variants, as follows:

  • Creating personalized threads, as in the example, using a special format for the name or even creating your own Thread class that would inherit 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

You can add anything else you can imagine to the preceding list. 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 will have to review the code to guarantee that all the threads are created using the same factory.

See also

  • The Implementing the ThreadFactory interface to generate custom threads and Using our ThreadFactory in an Executor object recipes in Chapter 8, Customizing Concurrency Classes