Wednesday, July 30, 2014

Thread Factory in Java

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.
In this post, 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.

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.


ThreadFactory
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.

ThreadFactory is an interface that is meant for creating threads instead of explicitly creating threads by calling new Thread(). An object that creates new threads on demand. Using thread factories removes hardwiring of calls to new Thread, enabling applications to use special thread subclasses, priorities, etc.

For example, assume that you often create high-priority threads. You can create a MaxPriorityThreadFactory to set the default priority of threads created by that  factory to maximum priority


With the use of ThreadFactory, you can reduce boilerplate code to set thread priority, name, thread-pool, etc.

Example


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.



If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

No comments:

Post a Comment