Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

limiting number of threads used by the JVM

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.

  1. Some random guy send me a code which my computer is going to execute
  2. Code must be execute within using maximum of k threads
  3. All must be automated - working like SPOJ, ideone, etc.
like image 390
abc Avatar asked Jun 27 '13 11:06

abc


1 Answers

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.

like image 87
Raedwald Avatar answered Sep 30 '22 18:09

Raedwald