Limit the number of threads used by the JVM

How to set a limit on the number of threads that someone can create? I am using code (something like ideone) and I want to limit the number of threads that it can cause. How to do it? Some jvm settings or something else?

EDIT I ​​am adding more of the above information because some people do not get my point.

  • Some random guy will send me a code that my computer is about to execute.
  • Code must be executed using a maximum of k threads
  • Everything needs to be automated - works like SPOJ, ideone, etc.
+7
source share
3 answers

On Linux, you can run the program as a separate user and use the ulimit -u nprocs shell command to limit the number of threads (processes) for this user. If you try to exceed the limit, the JVM OutOfMemoryError .

But why do you want to do this? Are you worried that the program will consume all the resources of the computer processor? If so, you might want to run the JVM with a lower scheduling priority using nice , so other processes will take precedence over the CPU:

  NPROCS=100 # for example NICENESS=13 # for example ulimit -u $NPROCS nice -n $NICENESS java ... 

Using nice in this way should reduce the priority of all threads, but it is not clear that this is done for Linux .

+6
source

You can create your own subclass for a thread that performs the required check in the constructor (s) or in the start method.

To ensure that the executable code uses your own thread class, you must load the code using your own custom class loader, and this class loader just picks up any request for the java.lang.Thread class and instead produces your own class (this concept could be extended to other classes).

Warning: implementing this rule is not trivial.

+2
source

AFAIK, Limit depends only on the OS, and not on the JVM.

And you can control them using the Executor service

An executor that provides methods for managing termination and methods that can provide the future for tracking the progress of one or more asynchronous tasks.

 ExecutorService pool = Executors.newFixedThreadPool(n); 
0
source

All Articles