如何在java中设置进程的CPU和内存限制?
你好 我想用java和tomcat服务器制作一个网站。 该网站将为每个用户在服务器上的所有进程设置 CPU 和内存限制。例如,每个用户 %3 cpu 和 100mb 内存限制。
我怎样才能做到呢? 谢谢
Hi
I want to make a website using java and tomcat server.
The website will set cpu and memory limit for each user for their all process on a server. For example for each user %3 cpu and 100mb memory limit.
How can I make it?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于一个 Tomcat 进程来说这是不可能的。您需要生成多个子进程,每个子进程都有自己的(-Xmx100m 或特定于操作系统的内存配额)和特定于操作系统的设置来控制 CPU 配额。
根据用户的恶意程度,您还可以限制可用文件描述符的数量、端口范围、磁盘配额等。最后,将每个用户的进程放入虚拟机和/或监狱中可能是值得的。
It is not possible with one Tomcat process. You need to spawn multiple child processes, each with it's own (-Xmx100m OR OS-specific memory quota) AND OS-specific settings to control CPU quota.
Depending on how malicious your users may become, you may also restrict number of available file descriptors, port ranges, disk quota, etc. At the end it may worth it to place each user's process into a VM and/or jail.
Java 中没有可用的机制来强制限制线程资源的使用。做到这一点的唯一方法是让底层操作系统来执行此操作,这很可能需要您为每个限制生成一个单独的 JVM,并且它不能跨平台移植。
请注意,您可以对函数调用设置超时限制(使用 Executor)并中断大多数操作。这对你来说可能已经足够了。如果您需要更多,则再次需要操作系统介入。
There is no mechanism available in Java for enforcing limits on threads resource usage. The only way you can do this, is by getting the underlying operating system to do it which will most likely require you to spawn a separate JVM for each restriction, and it will not be portable across platforms.
Note that you can put a timeout limit on a function call (using Executor) and have most operations interrupted. This might be good enough for you. If you need more, you again need the operating system to step in.