简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM