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

Java 9 Concurrency Cookbook, Second Edition
By :

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:
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.
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:
MyThreadFactory
and specify that it implements the ThreadFactory
interface:public class MyThreadFactory implements ThreadFactory {
private int counter; private String name; private List<String> stats; public MyThreadFactory(String name){ counter=0; this.name=name; stats=new ArrayList<String>(); }
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; }
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(); }
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(); } } }
Main
and implement the main()
method:public class Main { public static void main(String[] args) {
MyThreadFactory
object and a Task
object:MyThreadFactory factory=new MyThreadFactory("MyThreadFactory"); Task task=new Task();
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(); }
System.out.printf("Factory stats:\n"); System.out.printf("%s\n",factory.getStats());
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:
Thread
class that would inherit the Java Thread
classYou 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.