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

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.

Related

What's difference between request's thread and program's thread?

I'm almost new to Java. I know multithreading is the action of separating program into several tasks so that they can run concurrently. I have two problems with this concepts.
First of all, it's been said that application server creates a thread per each request. I can't associate this per-request-thread with program's threads. Suppose a program in which there are 5 threads to do things concurrently. How that single thread per request is going to deal with the 5 threads of that program?
Secondly, I have problem grasping the idea of thread pool. Is it about the threads that application server creates per request or it's regarding programs's threads that do tasks concurrently?
I have problem grasping the idea of thread pool.
A simple thread pool is a collection of running threads (a.k.a., worker threads) in which, each thread continually tries to take a task object from a BlockingQueue, and when it gets one, it executes the task, and then goes back to the queue to wait for another one.
A task is an object with some well-known method that the worker calls in order to "execute" the task. E.g., in the thread pools defined by the Java standard library, task objects either are Runnable instances or Callable instances, and the worker executes a task by calling task.run() or by task.call().

How to shutdown the ThreadServiceExecutor where the number of threads is not initially known [duplicate]

This question already has answers here:
ExecutorService, how to wait for all tasks to finish
(16 answers)
Closed 5 years ago.
I am in the process of writing a code where whenever a folder is encountered it is supposed to start a new thread. The code looks like,
p
ublic void diff(File x,File y){
ThreadPoolExecutor executor=new ThreadPoolExecutor(10,30,2000,unit,BlockingQueue<Runnable> queue)
if(x.isDirecotry && y.isDirectory){
Runnable thread=new DThread(x,y);
Future<?> result=executor.submit(thread);
if(result.isDone()){
LOGGER.debug(thread.toString()+"has completed");
}
I am using ThreadPoolExecutor for this purpose. If I shutdown the ThreadPoolExecutor then it will not take up any new Threads. But there is a possibility of new threads starting after starting. If I do not shutdown the ThreadPoolExecutor then all the threads are executed but in the end the JVM is not terminating.
Please help how can I shutdown the threadPool only when all the threads are executed so that the JVM gets terminated. Also suggest if there is better way of implemention of thread pool.I want to use thread pool so that I can use threads from the pool instead of creating new thread everytime.
The things that you are submitting should not be threads (subtypes of Thread). They should be simple tasks: implementations of Runnable or Callable.
The way to shutdown the executor is to call shutdown() or shutdownNow() on it. The javadoc summary says:
void shutdown() -
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
List<Runnable> shutdownNow() - Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
The latter attempts to stop the tasks by interrupting them. However, if the task code does not check for interrupts, it will run to completion. (It also stops accepting new tasks.)
It sounds like shutdown() does what you want to do.
The problem lies in the fact where should I place the shutdown method.
You call it when you want to start shutting down.
Because there is a possibility that new threads may be coming after shutdown is being called.
Stop calling them threads. They are tasks.
Any tasks that are submitted after shutdown() has been called are rejected.
My question is how can I check whether all the tasks have finished executing and only then call shutdown. If I call with the initiation of each task then it will not allow new tasks later on.
The correct time to call shutdown() is when your application has finished submitting tasks to the executor.
Maybe your conceptual problem is the scoping of the executor service. Your example code seems to show that each call to diff is creating a new service object. That means that you would have lots of independent thread pools ... and no reuse of threads. What you should really do is to create a "global" thread pool and have multiple calls to diff submit tasks to the same pool.

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?

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 does java.util.concurrent.Executor work?

How does java.util.concurrent.Executor create the "real" thread?
Suppose I am implementing Executor or using any executor service (like ThreadPoolExecutor). How does JVM internally work?
It calls ThreadFactory. Look at the Executors class. Note they all have an overloaded argument where you can supply a ThreadFactory implementation. The ThreadFactory interface is basically
public Thread newThread(Runnable runnable);
and the default implementation if not supplied basically just is return new Thread(runnable);
Why override this - well it's very useful for setting the Thread name and daemon status among other things.
Executor is ready made thread management interface.
Depending on type of executor it creates one or more threads. After thread finishes its task executor stops them or leave running. You can also have executor that run scheduled tasks (for example every minute). This is good alternative for creating many (often thousand of threads) that are needed for just five seconds or plenty of threads that are used from time time.
If you specify number of threads to create and submit more tasks than thread quantity is -- all other Runnable objects will be queued until their turn will come. No JVM magic here just java code.

Categories