在内存超过给定阈值后暂停所有 运行 线程

Pause all the running Threads after a memory crosses a given threshold

我有一个要求,我有一个多线程 java 应用程序,我想监视应用程序中的内存使用情况。我想在内存超过 90% 时立即暂停执行程序服务中的所有 运行 线程。下面是一个示例代码,我已经写了,但是,我不确定如何暂停 threads.I 我试图每分钟轮询一次以检查内存利用率,但不确定如何暂停执行程序中的所有线程服务。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class PauseThreads {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();

for(int i=0;i<10;i++){
    exec.submit(new Workers());
}


ScheduledExecutorService schedule = (ScheduledExecutorService) Executors.newSingleThreadExecutor();
schedule.scheduleAtFixedRate( new Runnable(){

    @Override
    public void run() {
        Runtime runtime = Runtime.getRuntime();


        long maxMemory = runtime.maxMemory();
        long allocatedMemory = runtime.totalMemory();

        if( (allocatedMemory / maxMemory ) > 0.9 ){
            //pause all the threads running under the exec
        }

    }

},  0, 60, TimeUnit.SECONDS);
}
}

class Workers implements Runnable{

@Override
public void run() {

    // do some work

}

}

请指教,需要做哪些改动,或者有没有其他更好的approach.Thanks。

我不知道如何监控堆使用情况,但是...

...你说 "pause" 好像这是一个线程要对另一个线程做的事情。

坏主意。

如果您是一个线程,并且占用了所有内存,如果我可以 "pause" 您有什么用呢?在 "paused?"

时如何释放正在使用的任何内存

你想要的是让每个工作线程做这样的事情:

while (true) {
    waitUntilTheresEnoughAvailableResources();
    acquireSomeResources();
    doAUnitOfWorkWork();
    freeResources();
}

您可以使用 ReentrantLock,如下例所示。您的 Worker 线程需要偶尔调用 check() 方法

public class MemoryAwait {

    private Lock lock = new ReentrantLock();
    private Condition memoryAvailable = lock.newCondition();


    public MemoryAwait() {
        ScheduledExecutorService schedule = (ScheduledExecutorService) Executors.newSingleThreadExecutor();
        schedule.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (enoughFreeMemory()) {
                    memoryAvailable.notify();
                }
            }
        }, 0, 60, TimeUnit.SECONDS);
    }

    public void check() throws InterruptedException {
        try {
            lock.lock();
            while (!enoughFreeMemory()) {
                memoryAvailable.await();
            }
        } finally {
            lock.unlock();
        }
    }

    private boolean enoughFreeMemory() {
        Runtime runtime = Runtime.getRuntime();
        long maxMemory = runtime.maxMemory();
        long allocatedMemory = runtime.totalMemory();
        return allocatedMemory / maxMemory < 0.9;
    }
}