I read it is not possible to restart the same Thread
. If it should be restarted, then you have to create a new Thread
.
But the thing is, the threads are limited, you can not create 40,000 threads because the operating system can only create 15,000 threads. (This is just an example).
Is there another possibility?
CodePudding user response:
But the thing is, the threads are limited, you can not create 40,000 threads because the operating system can only create 15,000 threads. (This is just an example).
Yes, that's confusing - but you're mixing terms.
A java java.lang.Thread
object is not an OS-level thead.
You can make a million or so Thread objects. Go ahead, try it.
You would not be able to simultaneously start all 1 million of em, however - start()
causes things to occur, eventually leading to an 'OS level thread' to be created.
Once a thread ends, the java.lang.Thread
object will stick around, but the OS level thread won't. Hence, your central problem thesis, which I'll summarize as:
Restarting an existing java.lang.Thread object is better than creating a new java.lang.Thread object, because I read that you can only have 40k or so java.lang.Thread objects
Is just flat out wrong. There is zero benefit between a hypothetical re-use of a j.l.Thread object by 'restarting' it (which implies it has ended), vs. just making a new object instead once the 'old' one has ended.
What you'd have to do if you want to 'restart' a thread is to have a run()
method (the one that the thread ends up running in a new thread) that is a frameworky thing: It checks a queue of jobs, pulls one queue off the top, runs it, and then goes back to checking the queue. This is tantamount to 'reusing a thread', though you're now just reinventing what ExecutorPool
(baked into core java itself) and friends already do.
ExecutorPools are probably a good idea. However, they don't 'solve' your problem. Your problem isn't actually a problem.
CodePudding user response:
Use an Executor
or ExecutorService
. Class Executors
has some factory methods for those. By using one that uses a thread pool you can submit actions without threads necessarily being created for each separate action.
CodePudding user response:
You can use a thread pool. Database connections are often managed in a thread pool, for example. After it has done its work (e.g., queried some data), the thread returns to the pool, and can be reused.
The other thing you may be missing is: while you cannot have e.g., 40,000 threads at a time, nothing prevents you from creating new threads after old ones have finished.