I have an application which massively creates threads. As result I get an OutOfMemoryError. My idea is to wait until there is enough free space to create the next Thread. But therefore I need to know how many memory I need to create a thread and if this amount of memory is available. Is there a way to get the amount of memory a thread needs? And how can I determine if this amount of memory is available?
What I've already tried:
for (int i = 0; i < links.size(); i++) {
while(Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory() +
Runtime.getRuntime().freeMemory() < MEMORY_THRESHOLD) {
synchronized (lock) {
lock.wait(10);
}
}
Thread t = new Thread(new Task(links.get(i)));
t.setDaemon(true);
t.start();
}
But even when I use 100MB as threshold I get an OutOfMemoryError.
.maxMemory() - untime.getRuntime().totalMemory(), maxMemory and totalMemory sound different to me