gpt4 book ai didi

java - Java内存泄漏?用信号量实现哲学家就餐

转载 作者:行者123 更新时间:2023-11-30 04:17:04 26 4
gpt4 key购买 nike

我似乎在 Java 中造成了内存泄漏,我什至没有意识到这是可能的。我根据 Andrew Tanenbaum 的《现代操作系统》一书中的数字实现了一种解决哲学家就餐并发问题的解决方案。

只要不死锁并且不使任何线程挨饿,它就可以正常工作。然而......在相当短的时间内,它消耗了大约 1GB 的 RAM(基于观察 Windows 系统资源),然后 Eclipse 崩溃并显示消息 Unhandled event Loop exception
Java堆空间
.

问题:

  • 造成这种情况的原因是什么?
  • 我可以使用什么工具(除了让我失望的逻辑演绎之外)来回答这个问题? Java/内存分析等?我对 Eclipse 内置的调试器之外的此类工具缺乏经验。

SSCCE:

import java.util.concurrent.Semaphore;

public class SemaphoreDiningPhilosophers {

static enum State {
THINKING,
HUNGRY,
EATING
}

static int N = 5;

static Semaphore mutex;
static Semaphore[] sem_philo;
static State[] states;

static void philosopher(int i) throws InterruptedException {
states[i] = State.THINKING;
System.out.println("Philosopher #" + (i + 1) + " is thinking.");

while (true) {
takeForks(i);
eat(i);
putForks(i);
}
}

static void takeForks(int i) throws InterruptedException {
mutex.acquire();
states[i] = State.HUNGRY;
test(i);
mutex.release();
sem_philo[i].acquire();
}

static void eat(int i) {
System.out.println("Philosopher #" + (i + 1) + " is eating.");
}

static void putForks(int i) throws InterruptedException {
mutex.acquire();
states[i] = State.THINKING;
System.out.println("Philosopher #" + (i + 1) + " is thinking.");
test((i + 4) % N);
test((i + 1) % N);
mutex.release();
}

static void test(int i) {
if (states[i] == State.HUNGRY
&& states[(i + 4) % N] != State.EATING
&& states[(i + 1) % N] != State.EATING) {
states[i] = State.EATING;
sem_philo[i].release();
}
}

public static void main(String[] args) {

mutex = new Semaphore(1);
sem_philo = new Semaphore[N];
for (int i = 0; i < N; i++) {
sem_philo[i] = new Semaphore(0);
}
states = new State[N];

Thread[] philosophers = new Thread[N];
for (int i = 0; i < N; i++) {
final int i2 = i;
philosophers[i2] = new Thread(new Runnable() {
public void run() {
try {
philosopher(i2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
philosophers[i2].start();
}
}

}

最佳答案

问题在于程序生成的输出量。如果 Eclipse 试图将所有内容都存储在输出控制台中,它将耗尽内存。

关于java - Java内存泄漏?用信号量实现哲学家就餐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18122499/

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