Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread sleeping in a Thread-Pool

Let's say we have a thread-pool with a limited number of threads.

Executor executor = Executors.newFixedThreadPool(3);

Now let's say one of the active tasks must sleep for 3 seconds (for whatever reason).

executor.execute(() -> {
    try {
        Thread.sleep(3000L);
    } catch (InterruptedException ignore) {}
});

How can we implement such a thread-pool in way that, when a task sleeps (or waits on a monitor/condition), the thread1 can be used effectively to run another task?

1By thread I do not mean the "physical" Java thread, because that would be impossible while the thread is asleep. What I mean is, the thread-pool to have an abstract implementation which virtually seems to allow a thread to run another task during sleeping. The key point is that there are always N simultaneously running (non-sleeping) tasks.

Somewhat similar to the way a monitor handles access to a critical region:

  • If a thread waits on a resource, the resource can be used by another thread.
  • If the thread is notified, it is placed into the waiting set to (re-)gain access to that resource.
like image 231
Snackoverflow Avatar asked Mar 21 '19 16:03

Snackoverflow


People also ask

What happens if a thread goes to sleep?

Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

Does thread sleep block other threads?

Sleep method causes the current thread to immediately block for the number of milliseconds or the time interval you pass to the method, and yields the remainder of its time slice to another thread. Once that interval elapses, the sleeping thread resumes execution. One thread cannot call Thread. Sleep on another thread.

What is thread pool thread?

A thread pool is a collection of worker threads that efficiently execute asynchronous callbacks on behalf of the application. The thread pool is primarily used to reduce the number of application threads and provide management of the worker threads.

What is thread sleep method?

Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can't be negative, else it throws IllegalArgumentException .


1 Answers

What you are asking for is essentially implementing coroutines/fibers on top of JVM/OS thread. Nice talk was given by Sanhong Li about the way how Alibaba's engineers implemented such construction - the idea is instead of relying on OS thread scheduler you need to rely on your own Selector.

See also Loom project for fibers (user-land green threads).

like image 162
EvgeniyK Avatar answered Sep 19 '22 10:09

EvgeniyK