Java thread pool size (Executors) - java

I have an application that has 3 threads which I'm going to switch over to be managed by ScheduledExecutorService. When creating an instance of this you must specific the thread pool size but what is this? Does this mean if I'm planning on running 3 tasks I should create a thread pool size of 3 one for each?

Assuming You have created ScheduledExecutorService like this
ScheduledExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new Runnable() {
public void run() {
System.out.println("Asynchronous task");
}
});
executorService.shutdown();
Now what is happening here :
First an ExecutorService is created using the newFixedThreadPool()
factory method. This creates a thread pool with 10 threads
executing tasks.
Second, an anonymous implementation of the Runnable interface is
passed to the execute() method. This causes the Runnable to be
executed by one of the threads in the ExecutorService.
Thread pools manage a pool of worker threads. The thread pools contains a work queue which holds tasks waiting to get executed.
Now Coming to :
Does this mean if I'm planning on running 3 tasks I should create a
thread pool size of 3 one for each?
Yes so that all 3 task can be executed parallely .
Now here is a nice article about How big should our thread pool be?

Related

How can i create Internal Thread pool for a single Thread in java

I have Quartz Job reading from the Queue and writing to the Queue. Reading is done in main thread and the Writing is done in the Sub thread.
How can i create a pool and get sub thread from that pool
You can use java Executor framework.
Example:
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();

Is it possible to have a set of thread pools that share threads from a large thread pool instead of creating new thread?

Is it possible to have a set of thread pools that share threads from a large thread pool instead of creating new thread?
In our RESTful API application, a request may involve several parallel tasks. To improve the performance, we want to execute parallel tasks in a thread pool which has a fixed number (say 200) of threads. But we also want to limit the max number of threads that each request can use. So I am thinking if it is possible to create a sub thread pool with a maximum pool size for each request, which does not create thread by itself but tries to fetch a new thread from the global thread pool and put job into queue if there is no available threads.
Has anyone done something similar? Or is there any other better solution?
Thanks!!
Instead of thread pools, think of executors. An executor consists of 2 things: a job queue and a thread pool. What you need is a light-weight executor for each request which has a job queue but has no threads. Instead, it passes jobs from its queue to the main executor (which owns all the threads). The trick is that the light-weight executor counts how many jobs it has submitted to the main executor, and stops passing jobs when the number exceeds the limit. Each job, before being passed to the main executor, is wrapped in an object of type Runnable which a) has the reference to the parent light-weight executor, b) executes the wrapped job and c) notifies the referenced executor when the job is finished so that the executor can pass another job to the main executor (or just decrease the job counter, if there is no jobs in the queue).
You could create a thread pool for every task e.g. Executors.newFixedThreadPool(10) This will do what you ask for with the inefficiency of potentially creating threads that a particular task instance doesn't need.

Java Thread Pool ExecutorService: Threads execution order

As we create a Thread pool using Java's Executor service and submit threads to this thread pool, what is the order in which those threads get executed?
I want to ensure that threads submitted first, execute first.
For example, in the code below, I want first 5 threads to get executed first, followed by the next 5 threads and so on...
// Create a thread pool of 5 threads.
ScheduledExecutorService exService = Executors.newScheduledThreadPool(5, new ModifiedThreadFactory("ReadThreadPool"));
// Create 100 threads.
MyThread[] threads = createMyThreads(100);
// Submit these 100 threads to thread pool for execution.
for(MyThread thread : threads) {
exService.submit(thread);
}
Does Java's Thread Pool provide any API for this purpose, or do we need to implement a FIFO queue at our end to achieve this.
If Java's thread pool does not provide any such functionality, I am really interested to understand the reason behind the non-existence of this functionality as it appears like a very common use-case to me.
Is it technically not possible (which I think is quite unlikely), or is it just a miss?
That's the default behavior. ScheduledThreadExecutor (that you're using although you're not scheduling anything) extends from ThreadPoolExecutor. Tasks submitted to a ThreadPoolExecutor are stored in a BlockingQueue until one thread is available to take them and execute them. And queues are FIFO.
This is decscribed in details in the javadoc.
Threads do not get executed. Threads are the entities running taska like Runnable and Callable . Submiting such a task to a executor service will put it in it's inner BlockingQueue until it gets picked up by a thread from it's thread pool. This will still tell you nothing about the order of execution as different classes can do different things while implementing Runnable

how many threads are created in this code? [duplicate]

This question already has answers here:
Confused on Java ThreadPool
(2 answers)
Closed 8 years ago.
Executors.newFixedThreadPool(5) creates 5 threads in the pool, and then in the loop another 100 threads are created. Is this understanding right? Then the 5 threads in the pool will execute each thread in the queue of 100 worker thread.
so in total there are 105 threads created? I had thought only 5 threads are created, but each Runnable is also a thread.
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 100; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);
}
executor.shutdown();
Executors.newFixedThreadPool(5) creates 5 threads in the pool, and then in the loop another 100 threads are created. Is this understanding right? Then the 5 threads in the pool will execute each thread in the queue of 100 worker thread.
This is not correct. The fixed-size thread pool executor will create 5 worker threads. Your 100 Runnables are all added to a queue that these 5 threads are pulling from. So only 5 of your Runnables are executing at any given time. There are 5 threads (plus the main thread, and possibly the EDT if you're using Swing, and of course any other unrelated threads that you've explicitly created).
I had thought only 5 threads are created, but each Runnable is also a thread.
A Runnable is not a thread. A Runnable, as its name implies, is just something that can be run. In the case of the fixed-size thread pool, it is being run by one of the threads in the pool. From the documentation for Runnable (emphasis mine):
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.
I believe the source of your confusion may be that your Runnables are innapropriately named WorkerThread, even though they are not threads. Additionally, you may be confused by the fact that Thread also implements Runnable. In fact, this literally means that a Thread is a Runnable, not that a Runnable is a Thread -- and a Thread isn't even a thread until it's started.
A Runnable is not a running thread. Neither is a Callable nor a Thread for that matter.
A thread is only created at the JVM level when you .start() a Thread (which will .run() a Runnable or .call() a Callable); until then, they are just normal, regular objects.
As you use an Executor, it is the executor which will manage your Runnables or Callables and start "real" threads when it can do so.
Don't confuse the Thread class with a thread. Java uses the Thread class to spawn threads, but it's not necessarily a 1-to-1 mapping.
In your code, it seems your WorkerThread class is a sub class of Thread. However, Thread also implements Runnable and that's how your ExecutorService is using it. It just invokes its run() method within one of the 5 threads that it started.
how many threads are created in this code?
All the threads started by the ExecutorService.
A Runnable is just an interface like any other interface. Also Thread is just a class not a separate thread. An actual thread is not created until you call the start() method on Thread class.
"Number of threads in pool will be fixed. If requests come more than the number of threads, they will wait in queue. If a thread dies or terminated, a new thread will be created." More here
In this case, only maximum number of 5 threads would be exist.

java Multithreading using Executor

I have 2 classes that implement Runnable.I need to create 10 threads to execute them.I use the following code.
ExecutorService es = Executors.newFixedThreadPool(10);
Runnable r=new TestThread1();
Runnable r1=new TestThread2();
es.execute(r);
es.execute(r1);
but since only 2 runnables exist,only 2 threads are being used to execute.how shud i increase the no of threads
Threads will be created as you submit more jobs to the executor. If the number of submitted jobs exceed 10 (in this case), the new jobs will be queued. When threads become free they will be used to run the queued jobs. If you want the executor to create 10 threads, you need to submit 10 jobs:
for (int i = 0; i < 5; ++i) {
if (!es.isShutdown()) {
es.submit(new TestThread1());
es.submit(new TestThread2());
}
}
One Runnable can only run on one Thread. It doesn't get split up across multiple threads automatically.
If you want to utilise your entire thread pool, create more runnable objects.
Executors.newFixedThreadPool(size) returns ThreadPoolExecutor instance.
JavaDoc of ThreadPoolExecutor says: ” When a new task is submitted in method ThreadPoolExecutor.execute, and fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle.”
That is, you have to execute 10 threads to fill the pool.

Categories