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:
- Create a class called
MyThreadFactoryand specify that it implements theThreadFactoryinterface:
public class MyThreadFactory implements ThreadFactory {- 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>();
}- Implement the
newThread()method. This method will receive aRunnableinterface and return a thread object for thisRunnableinterface. 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;
}- Implement the
getStatistics()method; it returns aStringobject 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();
}- Create a class called
Taskand specify that it implements theRunnableinterface. 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();
}
}
}- Create the main class of the example. Create a class called
Mainand implement themain()method:
public class Main {
public static void main(String[] args) {- Create a
MyThreadFactoryobject and aTaskobject:
MyThreadFactory factory=new MyThreadFactory("MyThreadFactory");
Task task=new Task();- Create 10
Threadobjects using theMyThreadFactoryobject 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();
}- Write the statistics of the thread factory in the console:
System.out.printf("Factory stats:\n");
System.out.printf("%s\n",factory.getStats());- 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
Threadclass that would inherit the JavaThreadclass - 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