Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Java 9 Concurrency Cookbook, Second Edition

You're reading from   Java 9 Concurrency Cookbook, Second Edition Build highly scalable, robust, and concurrent applications

Arrow left icon
Product type Paperback
Published in Apr 2017
Publisher Packt
ISBN-13 9781787124417
Length 594 pages
Edition 2nd Edition
Languages
Concepts
Arrow right icon
Author (1):
Arrow left icon
Javier Fernández González Javier Fernández González
Author Profile Icon Javier Fernández González
Javier Fernández González
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Thread Management FREE CHAPTER 2. Basic Thread Synchronization 3. Thread Synchronization Utilities 4. Thread Executors 5. Fork/Join Framework 6. Parallel and Reactive Streams 7. Concurrent Collections 8. Customizing Concurrency Classes 9. Testing Concurrent Applications 10. Additional Information 11. Concurrent Programming Design

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
You have been reading a chapter from
Java 9 Concurrency Cookbook, Second Edition - Second Edition
Published in: Apr 2017
Publisher: Packt
ISBN-13: 9781787124417
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image