Java需要新线程的内存 [英] Java needed memory for new thread

查看:99
本文介绍了Java需要新线程的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以大规模创建线程的应用程序.结果,我收到一个 OutOfMemoryError .我的想法是等到有足够的可用空间来创建下一个线程.但是因此我需要知道创建一个线程需要多少内存,以及是否有可用的内存量.有没有办法获取线程所需的内存量?以及如何确定此内存量是否可用?

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?

我已经尝试过的:

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();
}

但是即使我使用100MB作为阈值,我也会收到 OutOfMemoryError .

But even when I use 100MB as threshold I get an OutOfMemoryError.

推荐答案

不,您可以删除此代码,而使用ThreadPool.您尝试执行的操作相当困难,您应该使用必须执行多线程处理或完全不执行的更高抽象.

No, you go and delete this code and use a ThreadPool instead. What you trying to do is quite hard and you should be using the higher abstraction you have to do multithreading or you don't do it at all.

签出执行器,当前它们是更高的抽象. 如果您的任务是受计算约束的,那么Java 7中的ForkJoin是您的朋友,只要知道如何将问题递归地划分为子问题,就不必担心池的大小.

Check out Executors, currently they are the higher abstraction. If your tasks are compute bound then ForkJoin in Java 7 is your friend and you don't need to bother about the pool size as long as you know how to recursively divide your problem into subproblems.

这篇关于Java需要新线程的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆