I would like to know the difference between these 2 methods:
public static ExecutorService newFixedThreadPool(int nThreads)
and
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory tf)
Obviously one takes a specified ThreadFactory for threads creation. However I would like to know what kind of standard ThreadFactory the former use?
Why is it convenient using the latter rather than the former or vice-versa?
Thanks in advance.
DefaultThreadFactory,
New threads are created using a ThreadFactory. If not otherwise
specified, a Executors.defaultThreadFactory() is used, that creates
threads to all be in the same java.lang.ThreadGroup and with the same
NORM_PRIORITY priority and non-daemon status. By supplying a different
ThreadFactory, you can alter the thread's name, thread group,
priority, daemon status, etc. If a ThreadFactory fails to create a
thread when asked by returning null from newThread, the executor will
continue, but might not be able to execute any tasks. Threads should
possess the "modifyThread" RuntimePermission. If worker threads or
other threads using the pool do not possess this permission, service
may be degraded: configuration changes may not take effect in a timely
manner, and a shutdown pool may remain in a state in which termination
is possible but not completed.
Reference -
But you can encapsulate the thread creation in your ThreadFactory, what actaully usage of Factory pattern.
For Example -
class SimpleThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
// do something
return new Thread(r);
}
}
For reference please check - documentation and also find a good answer.
The first one uses the DefaultThreadFactory which is an inner class of Executors. When you define your own ThreadFactory you can influence the created Threads. You can choose their name, priority, etc.
The first uses Executors.defaultThreadFactory to create threads with the first version. You would use the first version if you don't care how the threads are created, and the second if you need to impose some custom settings on the threads when they are created.
Related
I have a list of objects, from which depending on user interaction some objects need to do work asynchronically. Something like this:
for(TheObject o : this.listOfObjects) {
o.doWork();
}
The class TheObject implements an ExecutorService (SingleThread!), which is used to do the work. Every object of type TheObject instantiates an ExecutorService. I don't want to make lasagna code. I don't have enough Objects at the same time, to make an extra extraction layer with thread pooling needed.
I want to cite the Java Documentation about CachedThreadPools:
Threads that have not been used for sixty seconds are terminated and
removed from the cache. Thus, a pool that remains idle for long enough
will not consume any resources.
First question: Is this also true for a SingleThreadExecutor? Does the thread get terminated? JavaDoc doesn't say anything about SingleThreadExecutor. It wouldn't even matter in this application, as I have an amount of objects I can count on one hand. Just curiosity.
Furthermore the doWork() method of TheObject needs to call the ExecutorService#.submit() method to do the work async. Is it possible (I bet it is) to call the doWork() method implicitly? Is this a viable way of designing an async method?
void doWork() {
if(!isRunningAsync) {
myExecutor.submit(doWork());
} else {
// Do Work...
}
}
First question: Is this also true for a SingleThreadExecutor? Does the thread get terminated?
Take a look at the source code of Executors, comparing the implementations of newCachedThreadPool and newSingleThreadExecutor:
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
The primary difference (of interest here) is the 60L, TimeUnit.SECONDS and 0L, TimeUnit.MILLISECONDS.
Effectively (but not actually), these parameters are passed to ThreadPoolExecutor.setKeepAliveTime. Looking at the Javadoc of that method:
A time value of zero will cause excess threads to terminate immediately after executing tasks.
where "excess threads" actually refers to "threads in excess of the core pool size".
The cached thread pool is created with zero core threads, and an (effectively) unlimited number of non-core threads; as such, any of its threads can be terminated after the keep alive time.
The single thread executor is created with 1 core thread and zero non-core threads; as such, there are no threads which can be terminated after the keep alive time: its one core thread remains active until you shut down the entire ThreadPoolExecutor.
(Thanks to #GPI for pointing out that I was wrong in my interpretation before).
First question:
Threads that have not been used for sixty seconds are terminated and removed from the cache. Thus, a pool that remains idle for long enough will not consume any resources.
Is this also true for a SingleThreadExecutor?
SingleThreadExecutor works differently. It don't have time-out concept due to the values configured during creation.
Termination of SingleThread is possible. But it guarantees that always one Thread exists to handle tasks from task queue.
From newSingleThreadExecutor documentation:
public static ExecutorService newSingleThreadExecutor()
Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.)
Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.
Second question:
Furthermore the doWork() method of TheObject needs to call the ExecutorService#.submit() method to do the work async
for(TheObject o : this.listOfObjects) {
o.doWork();
}
can be changed to
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
public void run() {
System.out.println("Asynchronous task");
}
});
executorService.shutdown();
with Callable or Runnable interface and add your doWork() code in run() method or call() method. The task will be executed concurrently.
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
Use LinkedBlockingQueue, But does ConcurrentLinkedQueue should be more efficient , which is no-blocking and lock free?
The answer is simple: ConcurrentLinkedQueue is not a BlockingQueue, but LinkedBlockingQueue is. The ThreadPoolExecutor constructors expect BlockingQueues, so that Executors creates instances also with other implementations of BlockingQueue, like SynchronousQueue or ArrayBlokingQueue (depending on the factory method you call in Executors).
So, the more general question is: why BlockingQueue and not a simple Queue. And here the answer is again simple: the BlockingQueue interface has more useful methods. E.g a method tell if an element could be inserted in the queue without violating the capacity restrictions (and without throwing Exception, check BlockingQueue.offer()). Or some methods block if the queue has no elements (which again has a timed poll() and not timed version take()). So, if you would check the implementation of the ThreadPoolExecutor, you would see that it calls these convenient methods that miss in the Queue interface.
If you submit Runnable objects to the queue and there are no running threads to consume those tasks, they of course will not be executed. When the queue becomes empty, the pool must block and wait for more tasks. So, to implement this behavior we are using BlockingQueue while interacting with pool.
I want to use the same thread pool throughout my application. To this end, I can make ExecutorService static and global so that I can invoke ThreadUtil.executorService to get ExecutorService when I need it.
public class ThreadUtil {
public static final ExecutorService executorService = Executors.newCachedThreadPool();
}
Is it OK to instance multiple thread pools like this?
In addition, my application is a TCP server. If I don't know how big the pool should be, is it ok to simply use newCachedThreadPool?
When an instance with the same properties is to be used anywhere in your program, it is logical to declare it static and final instead of re-creating the instance each time but I would personally opt for a Singleton pattern instead of directly giving public access to the instance.
As for your second query, I don't see any problem with it. The first sentence of the documentation for newCachedThreadPool says
Creates a thread pool that creates new threads as needed
since you don't know how many threads will be created, this is the most logical choice.
Note that newCachedThreadPool will re-use old threads when they are available to increase performance.
I would not make it directly global. At least wrap it in a class so you can easily use more than one pool. Having a pool of thread pool is very useful when you need more than one kind of job/ jobs with different priority. Just put fewer threads in the other pool and/or lower priority threads (by over riding the thread factory). For a sample can see https://github.com/tgkprog/ddt/tree/master/DdtUtils/src/main/java/org/s2n/ddt/util/threads
Usage :
//setup
PoolOptions options = new PoolOptions();
options.setCoreThreads(2);
options.setMaxThreads(33);
DdtPools.initPool("poolA", options);
Do1 p = null;
// Offer a job:
job = new YourJob();
DdtPools.offer("poolA", job);
Also do not use a cached pool as it can grow as needed, not a good idea with TCP which can block indefinately. You want to use a controlled pool. The above library can be reinitialized if needed (increase number of threads while allowing current jobs to process before the old pool is discarded to GC).
Can make a utility jsp/ servlet for those ops like https://github.com/tgkprog/ddt/blob/master/Core/src/main/web/common/poolEnd.jsp and https://github.com/tgkprog/ddt/blob/master/Core/src/main/web/common/threads.jsp
If you have only ExecutorServivce for your application, you can proceed with static global.
newCachedThreadPool() and newFixedThreadPool() both does not provide control on queue of Callable/Runnable tasks. They use unbounded queue, which may result into degraded performance of the system with respect to performance.
I prefer to use ThreadPoolExecutor which provides better control on various parameters like Queue Size, Rejection Handler, Thread factory etc.
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler)
Or
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
Refer to below post for more details:
FixedThreadPool vs CachedThreadPool: the lesser of two evils
My question is : does it make sense to use Executors.newFixedThreadPool(1)??. In two threads (main + oneAnotherThread) scenarios is it efficient to use executor service?. Is creating a new thread directly by calling new Runnable(){ } better than using ExecutorService?. What are the upsides and downsides of using ExecutorService for such scenarios?
PS: Main thread and oneAnotherThread dont access any common resource(s).
I have gone through : What are the advantages of using an ExecutorService?. and Only one thread at a time!
does it make sense to use Executors.newFixedThreadPool(1)?
It is essentially the same thing as an Executors.newSingleThreadExecutor() except that the latter is not reconfigurable, as indicated in the javadoc, whereas the former is if you cast it to a ThreadPoolExecutor.
In two threads (main + oneAnotherThread) scenarios is it efficient to use executor service?
An executor service is a very thin wrapper around a Thread that significantly facilitates the thread lifecycle management. If the only thing you need is to new Thread(runnable).start(); and move on, then there is no real need for an ExecutorService.
In any most real life cases, the possibility to monitor the life cycle of the tasks (through the returned Futures), the fact that the executor will re-create threads as required in case of uncaught exceptions, the performance gain of recycling threads vs. creating new ones etc. make the executor service a much more powerful solution at little additional cost.
Bottom line: I don't see any downsides of using an executor service vs. a thread.
The difference between Executors.newSingleThreadExecutor().execute(command) and new Thread(command).start(); goes through the small differences in behaviour between the two options.
Sometimes need to use Executors.newFixedThreadPool(1) to determine number of tasks in the queue
private final ExecutorService executor = Executors.newFixedThreadPool(1);
public int getTaskInQueueCount() {
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
return threadPoolExecutor.getQueue().size();
}
does it make sense to use Executors.newFixedThreadPool(1)??
Yes. It makes sense If you want to process all submitted tasks in order of arrival
In two threads (main + oneAnotherThread) scenarios is it efficient to use executor service? Is creating a new thread directly by calling new Runnable(){ } better than using ExecutorService?.
I prefer ExecutorService or ThreadPoolExecutor even for 1 thread.
Refer to below SE question for explanation for advantages of ThreadPoolExecutor over new Runnable() :
ExecutorService vs Casual Thread Spawner
What are the upsides and downsides of using ExecutorService for such scenarios?
Have a look at related SE question regarding ExexutorService use cases :
Java's Fork/Join vs ExecutorService - when to use which?
Regarding your query in subject line (from grepcode), both are same:
newFixedThreadPool API will return ThreadPoolExecutor as ExecutorService:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
and
newSingleThreadExecutor() return ThreadPoolExecutor as ExecutorService:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
I agree with #assylias answer regarding similarities/differences.
Is creating a new thread directly by calling new Runnable(){ } better than using ExecutorService?
If you want to compute something on the returned result after thread compilation, you can use Callable interface, which can be used with ExecutorService only, not with new Runnable(){}. The ExecutorService's submit() method, which take the Callable object as an arguement, returns the Future object. On this Future object you check whether the task has been completed on not using isDone() method. Also you can get the results using get() method.
In this case, ExecutorService is better than the new Runnable(){}.
The ThreadPoolExecutor class allows to give a custom ThreadFactory to create new threads. However, I do not understand how these threads are used within sun's implementation of ThreadPoolExecutor.
This implementation creates new thread as follows:
private Thread addThread(Runnable firstTask) {
Worker w = new Worker(firstTask);
Thread t = threadFactory.newThread(w);
if (t != null) {
w.thread = t;
...
} ...
But in Worker's implementation, I do not see how field "thread" is used as the runner.
Furthermore, I do not understand how one can provide Thread with custom "run" method that
are reused (where reused - as in ThreadPoolExecutor - mean "they run multiple Runnable"). How can ThreadPoolExecutor reuse such threads to run multiple Runnable (given that the "target" Runnable in class Thread is set at construction time and there's no setter). ThreadPoolExecutor's documentation is as follows:
By supplying a different ThreadFactory, you can alter the thread's name, thread group, priority, daemon status, etc.
Does this mean that the "run" method of threads created by a custom ThreadFactory is not used ? That's the only way I would understand the "custom threads creation + thread 'reuse'" mechanism.
But in Worker's implementation, I do not see how field "thread" is used as the runner.
As newThread() documentation states, the newly created thread must run the Runnuble supplied as the argument to threadFactory.newThread(Runnuble).
This is the way new thread is used as the runner.
Furthermore, I do not understand how one can provide Thread with custom "run" method that are reused
Again, thread's run method must run the supplied Runnable.run() once. The thread poll supplies Worker which runs tasks in a loop.
Example of correct user-implemented thread:
public class ThreadTL extends Thread {
public ThreadTL(Runnable r) {
super(r);
setName(getName()+" DF "+executor.getClass().getSimpleName());
}
#Override
public void run() {
super.run();
}
}
One Runnable can call another. The Runnable you get passed is one which gets Runnables from the thread pools queue and runs those.