// Copyright (c) Keith D Gregory, all rights reserved
package com.kdgregory.example.memory;


/**
 *  Spawns threads that do nothing but sleep. Eventually, you'll get an
 *  <code>OutOfMemoryError</code> even though there's plenty of heap.
 */
public class ThreadExhaustion
{
    private static class Sleeper
    implements Runnable
    {
        public Sleeper(int counter)
        {
            // using System.err because it's unbuffered
            System.err.println(counter);
        }

        public void run()
        {
            try
            {
                Thread.sleep(3600000L);
            }
            catch (InterruptedException e)
            {
                // should never happen, but if it does we'll note it and
                // let the thread terminate
                System.out.println("thread interrupted");
            }
        }
    }
    
    
    public static void main(String[] argv)
    throws Exception
    {
        int counter = 1;
        while (true)
        {
            new Thread(new Sleeper(counter++)).start();
            if ((counter % 1000) == 0)
            {
                System.err.println("available memory = " + Runtime.getRuntime().freeMemory());
                System.err.println("pausing for 10 seconds so you can run pmap");
                Thread.sleep(10000L);
            }
        }
    }
}
