限制JVM使用的线程数 [英] limiting number of threads used by the JVM

查看:190
本文介绍了限制JVM使用的线程数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置某人可以创建的线程数限制?我所做的是运行某人的代码(类似于ideone),并希望限制他可以生成的线程数。怎么办?一些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. 一些随机的人发给我一个我的电脑要执行的代码

  2. 代码必须在最多k个线程内执行

  3. 所有必须自动化 - 像SPOJ,ideone等一样工作。


推荐答案

在Linux上,您可以作为单独的用户运行该程序,并使用shell命令 ulimit -u nprocs 来限制该程序的线程数(进程数)用户。如果尝试超出限制, JVM将抛出 OutOfMemoryError

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.

但你为什么要这样做?您是否担心该程序会占用计算机的所有CPU资源?如果是这样,您可能需要考虑以较低的调度优先级运行JVM,使用 nice ,因此其他进程将优先使用CPU:

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 ...

以这种方式使用 nice 应该降低所有线程的优先级,但目前尚不清楚它是否适用于Linux

Using nice in that manner should reduce the priority of all the threads, but it is not clear that it does so for Linux.

这篇关于限制JVM使用的线程数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆