简体   繁体   中英

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.

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 .

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM