0

Today I was just messing around with Threads in Java. After some tests, I decided to create & run 10,000 Threads and see if everything goes well or if some unexpected behavior will happen. Indeed, everything did go well, but I noticed something.

I spawned 10,000 Threads. My Memory usage was, as expected, over 1gb. But after every Thread was finished, the Memory usage dropped from 1gb to 200mb. So there is still ~180mb of memory which seems to be still busy. But why is that? Every Thread is finished, I double checked that.

Here is my test-code I have written. The program will spawn the threads, wait 10seconds and then the Thread should be finished. The BufferedReader is for the waiting, so the program will not instantly close.

 public static void main(final String[] args) throws IOException {

        final long startTime = System.currentTimeMillis();

        for (int i = 0; i < 10000; i++) {
            new Thread(new Runnable() {
                public void run() {
                    while (System.currentTimeMillis() - startTime < 10000) {
                        System.out.println(System.currentTimeMillis() - startTime);
                    }
                }
            }).start();
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        reader.readLine();
    }

Anyone have some ideas on this? Is there something I'm missing?

ljoedicke
  • 37
  • 7
  • The JVM doesn't necessarily release memory back to the OS if it isn't using it, though this is implementation-dependent. – kaya3 Aug 06 '20 at 23:50
  • Does this answer your question? [Release java memory for OS at runtime.](https://stackoverflow.com/questions/11919400/release-java-memory-for-os-at-runtime) – kaya3 Aug 06 '20 at 23:55
  • 2
    There's a lot missing. For example, 1. Objects are not logically freed until the GC runs, 2. OS allocations are expensive so the VM allocates and frees in large chunks to avoid talking to the OS for each object. 3. There's a limit to the granularity with which the VM can return memory to the OS even if it wanted to. 4. The VM needs some amount of internal data. For at least somewhat better results, compare Java's memory accounting (e.g. `Runtime.freeMemory`, not the OS process monitor) first after a warmup round and then after the main job and a GC. – that other guy Aug 07 '20 at 00:07
  • Some of the data might be held in an area that hasn't been subject to garbage collection yet (eg the tenured generation). – Mark Rotteveel Aug 07 '20 at 07:51
  • To test your assumption, you should also test with less or none Thread: you would see the consumption without object being created. – NoDataFound Aug 07 '20 at 08:47

0 Answers0