Reputation: 2381
How to set limit to the number of Thread that someone can create? What I do is running someone's code (something like ideone), and want to limit number of thread that he can spawn. How to do so? Some jvm setting or something else?
EDIT I add more specified info because some people are not gettin my point.
Upvotes: 7
Views: 8745
Reputation: 48702
On Linux, you could run the program as a separate user and use the shell command ulimit -u nprocs
to limit the number of threads (processes) for that user. If an attempt is made to exceed the limit, the JVM will throw an OutOfMemoryError
.
But why do you want to do this? Are you worried that the program will consume all the CPU resources of the computer? If so, you might want to consider running the JVM at lower scheduling priority, using nice
, so other processes will get preferential use of the CPU:
NPROCS=100 # for example
NICENESS=13 # for example
ulimit -u $NPROCS
nice -n $NICENESS java ...
Using nice
in that manner should reduce the priority of all the threads, but it is not clear that it does so for Linux.
Upvotes: 6
Reputation: 20069
You can create your own subclass for thread that performs the desired checking in the constructor(s) or in the start method.
To ensure the code you are running uses your custom thread class, you must load the code with your own custom class loader and that class loader simply catches any request for the java.lang.Thread class and hands out your custom class instead (the concept can be extended to other classes as well).
Warning: Implementing this properly is not trivial.
Upvotes: 2
Reputation: 122026
AFAIK,Limit is purely depends on OS not on JVM.
And you can Monitor them by a Executor service
An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.
ExecutorService pool = Executors.newFixedThreadPool(n);
Upvotes: 0