Throttling CPU/Memory usage of a Thread in Java?

前端 未结 9 2274
借酒劲吻你
借酒劲吻你 2020-12-07 13:00

I\'m writing an application that will have multiple threads running, and want to throttle the CPU/memory usage of those threads.

There is a similar question for C++,

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 13:33

    Thread.setPriority() may help, but it doesn't allow you to cap the CPU used by a thread. In fact, I've haven't heard of any Java library that does this.

    It might be possible to implement such a facility provided that your threads are prepared to cooperate. The key is to have the threads periodically call into a custom scheduler, and have the scheduler monitor thread CPU usage using JMX. But the problem is that if some thread doesn't make the scheduler call often enough it may well exceed the throttling limits. And there's nothing you can do about a thread that gets stuck in a loop.

    Another theoretical route to implementing would be to use Isolates. Unfortunately, you will be hard pressed to find a general purpose JVM that implements isolates. Besides, the standard APIs only allow you to control the isolate, not the threads within the isolate.

提交回复
热议问题