java Multithreading using Executor - java

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.

Related

Difference between a ExecutorCompletionService and a FixedThreadPool executor

As far as I know, executor completion service provides the output from the future object regardless of the order in which the task was requested in the inbound queue, i.e. whichever task is completed first the Result is put into the Outbound Queue. On the other hand, FixedThreadPool also executes the tasks parallelly, then what is the difference between the two? ( Not sure whether the FixedThreadPool gives the output sequentially in the order the tasks were fed to the inbound queue )
Thanks.
FixedThreadPool is one of the variations of Executor. It uses class ThreadPoolExecutor with same values for corePoolSize and maximumPoolSize. It means, if you create FixedThreadPool with 10 threads, it will always keep exact 10 threads. If any of these threads are terminated by running task - thread pool will create new ones to keep required amount.
CompletionService arranges that submitted tasks are, upon completion, placed on a queue.
It means, that all results of submitted tasks will be in a queue and you can process them later.
When you submit a task to a CompletionService, it creates a wrapper, so the result of async task is saved to queue. It doesn't create parallelism itself, instead CompletionService uses inside Executor for making parallel threads. You can pass FixedThreadPool inside, for example.
All tasks, submitted to FixedThreadPool and CompletionService will be done in parallel, without keeping the order.
CompletionService can be used, when you need to know when all of your tasks are finished. Example:
//Task extends Callable<Result>
List<Task> tasks = new ArrayList<Task>();
CompletionService<Result> cs = new ExecutorCompletionService<Result>(Executors.newFixedThreadPool(10));
tasks.forEach(task -> cs.submit(task));
for (int i = 0; i < tasks.size(); i++) { // you should know exact amount of submitted tasks
Result r = cs.take().get();
//process r
}
FixedThreadPool can be used in any other case, when you want to parallel threads without waiting for the results.
Also, note the difference between FixedThreadPool and CachedThreadPool. The first one is usually used when you need to keep threads alive and limit their amount. The seconds one is limited by system, it will process as many threads in parallel as possible. If a thread is in idle state in CachedThreadPool it will be automatically deleted after timeout (default is 60 seconds).

Java thread pool size (Executors)

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?

How can I implement FIFO queue of threads?

How can I implement FIFO queue of threads(tasks to do) and executing the threads one by one?
I mean for example, take the first thread and run it, and the second must wait for the end of execution of the first thread.
At the same time I must be able to add threads(tasks) to the queue.
Create a FixedThreadPool with only one thread and submit tasks to it. They will be executed one after the other, like in a FIFO queue:
ExecutorService es = Executors.newFixedThreadPool(1); // one thread only
// ...
for(Runnable r : myRunnables) {
es.submit(r);
}
As Vakh said, use an ExecutorService to run the threads, however I would recommend using a SingleThreadExecutor. The SingleThreadExectutor is guaranteed to execute threads sequentially because unlike a FixedThreadPool it can not be reconfigured to use a different number of threads.
ExecutorService es = Executors.newSingleThreadExecutor(); // one thread only
// ...
for(Runnable r : myRunnables) {
es.submit(r);
}
You can also call Thread.join() to tell the current thread to block exectution until the other thread dies.
Thread t = new Thread(myRunnable);
t.join(); //Wait until t dies
There are variations of join which will set a maximum wait time
if you want all your threads to run at the same time but you don't want them to use a specific resource or task, then you can use Synchronized Methods

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.

Running at most n Java threads

I have a CPU intensive application, which can be written in Java. The application consists of few jobs (threads) that run independently.
If I start all the threads at once, the system will be overloaded. How could I start at most n threads at once, and when one thread finishes then a new one is started? By limiting the number of threads running at once, I intend to leave some other processors/cores available for other tasks.
Thanks
You should formulate your threads' tasks as Runnables or Callables and then submit them to a fixed thread pool executor. The executor will manage a pool of worker threads and run your tasks from an internal queue on those threads.
See Executors#newFixedThreadPool for a factory method that creates the type of executor you want.
Use a fixed size executor pool.
ExecutorService executor = Executors.newFixedThreadPool(4);

Categories