Why ThreadPoolExecutor behaves differently when running Java program in Eclipse and from command line?

青春壹個敷衍的年華 提交于 2019-12-11 03:46:27

问题


Can anybody explain why this code throws OOME when I run it from Eclipse (Juno) but works fine when I run it from command line? I use -Xmx256M in both cases.

static class Task implements Runnable {
    byte[] buf = new byte[150000000];
    @Override
    public void run() {
    }
}

public static void main(String[] args) throws Exception {
    System.out.println(Runtime.getRuntime().maxMemory());
    ExecutorService ex = Executors.newSingleThreadExecutor();
    ex.submit(new Task()).get();
    ex.submit(new Task()).get();
}

Here is the Eclipse output

259522560
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at Test2$Task.<init>(Test2.java:7)
    at Test2.main(Test2.java:17)

I ran it on my notebook, cannot be sure how it behaves on other PCs.


回答1:


-- original response -- Eclipse is running with 256M, but did you edit the run config of the app to give the launched application 256aM as well? If not, it will run with default heap.

-- update after question updated --

I tested the code below, and it runs fine in eclipse and outside.

Does the OOME happen at the first run (eg, what does the following output?), and does changing the position of allocation affect things?:

public class Test {
    public static class Task implements Runnable {
        byte[] buf;
        int id;
        public Task(int i) {
            id = i;
        }

        @Override
        public void run() {
            buf = new byte[150000000];
            System.out.println("hi " + id);
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println(Runtime.getRuntime().maxMemory());
        ExecutorService ex = Executors.newSingleThreadExecutor();
        ex.submit(new Task(1)).get();
        ex.submit(new Task(2)).get();
    }
}


来源:https://stackoverflow.com/questions/13548809/why-threadpoolexecutor-behaves-differently-when-running-java-program-in-eclipse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!