gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:20:23 25 4
gpt4 key购买 nike

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

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

}

}

请提出建议,需要进行哪些更改,或者是否有其他更好的方法。谢谢。

最佳答案

您可以使用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;
}
}

关于java - 内存超过给定阈值后暂停所有正在运行的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31311931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com