Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reducing the number of OS threads used when have many sleeping threads

I'm having a system with hundreds of threads. Most of the thread are sleeping or waiting in a given time but they can wake up whenever they like. I would like to reduce the number of OS threads that are dedicated to my system. Do you know about a simple way of doing it? For example, is there a thread pool package that whenever a thread moves to sleep mode, it stores the state and kill the thread. whenever it wakes up, it starts new thread with the state of the old one.

Thanks

like image 715
DanielB Avatar asked Jun 15 '11 15:06

DanielB


People also ask

What happens if there are too many threads?

Problem with spawning multiple threads is, you will loose the performace because when number of threads are greater than number or cores then there will be context switching for processor time. One need to understand in any given point of time on a single core, only one thread can run.

Does sleeping on a thread consume resources?

For most cases, the resources consumed by a sleeping thread will be its stack space. Using a 2-threads-per-connection-model, which I think is similar to what you're describing, is known to cause great scalability issues for this very reason when the number of connections grow large.

How many threads are initialized when you start an application?

When a Java program starts up, one thread begins running immediately. This is usually called the main thread of our program because it is the one that is executed when our program begins.


2 Answers

Are you looking for something like ThreadPoolExecutor?

An ExecutorService that executes each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods.

Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.

like image 89
helpermethod Avatar answered Oct 01 '22 02:10

helpermethod


The thing you described is basically what thread is.

Now, you may know that your application logic only depends on a few variables, not everything on the thread stack. You only needs these few variables to recover from sleep. VM and OS can't know that, and they can't help you.

You must do it yourself. When your thread is about to retire, wrap the essential state up and store it on a queue. Then exit thread, or return it to a thread pool.

When a certain condition is met, lookup the state from the queue, create a new task based on it, and run the task on a new thread.

like image 44
irreputable Avatar answered Oct 01 '22 01:10

irreputable