Throttling CPU/Memory usage of a Thread in Java?

前端 未结 9 2246
借酒劲吻你
借酒劲吻你 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条回答
  • 2020-12-07 13:31

    You can assign different priorities to the threads so the most relevant thread get scheduled more often.

    Look at this answer to see if that helps.

    When all the running thread have the same priority they may run like this:

    t1, t2, t3,     t1, t2, t3,   t1, t2, t3
    

    When you assign a different priority to one of them it may look like:

    t1, t1, t1, t1,    t2,    t1, t1, t1 t3.
    

    That is, the first thread runs "more often" that the rest.

    0 讨论(0)
  • 2020-12-07 13:32

    Care of Java Forums. Basically timing your execution and then waiting when your taking too much time. As is mentioned in the original thread, running this in a separate thread and interrupting the work thread will give more accurate results, as will averaging values over time.

    import java.lang.management.*;
    
    ThreadMXBean TMB = ManagementFactory.getThreadMXBean();
    long time = new Date().getTime() * 1000000;
    long cput = 0;
    double cpuperc = -1;
    
    while(true){
    
    if( TMB.isThreadCpuTimeSupported() ){
        if(new Date().getTime() * 1000000 - time > 1000000000){ //Reset once per second
            time = new Date().getTime() * 1000000;
            cput = TMB.getCurrentThreadCpuTime();
        }
    
        if(!TMB.isThreadCpuTimeEnabled()){
            TMB.setThreadCpuTimeEnabled(true);
        }
    
        if(new Date().getTime() * 1000000 - time != 0)
            cpuperc = (TMB.getCurrentThreadCpuTime() - cput) / (new Date().getTime() *  1000000.0 - time) * 100.0;                  
        }
    //If cpu usage is greater then 50%
    if(cpuperc > 50.0){
         //sleep for a little bit.
         continue;
    }
    //Do cpu intensive stuff
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题