HJW
HJW

Reputation: 23443

How to hit java.lang.OutOfMemoryError by spawning threads?

I came across this blog site where the author is testing against the maximum number of threads before the machine throws a java.lang.OutOfMemoryError. However, in my below test codes, i am unable to hit the error despite the arbitrary large threads spawned.

    for (int i = 0; i < 1000000; i++) {
        Thread thread = new Thread(new Car());
        thread.setName(Integer.toString(i));
        thread.start();
    }

Upvotes: 0

Views: 647

Answers (3)

Ajay George
Ajay George

Reputation: 11875

Also take a look at the same problem which is covered in the JavaSpecialists Newsletter # 149 http://www.javaspecialists.eu/archive/Issue149.html

Here is a small piece of code that you can run to find out how many inactive threads you can start on your JVM:

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.CountDownLatch;

public class ThreadCreationTest {
  public static void main(String[] args)
      throws InterruptedException {
    final AtomicInteger threads_created = new AtomicInteger(0);
    while (true) {
      final CountDownLatch latch = new CountDownLatch(1);
      new Thread() {
        { start(); }
        public void run() {
          latch.countDown();
          synchronized (this) {
            System.out.println("threads created: " +
                threads_created.incrementAndGet());
            try {
              wait();
            } catch (InterruptedException e) {
              Thread.currentThread().interrupt();
            }
          }
        }
      };
      latch.await();
    }
  }
}

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039080

Try sleeping inside the thread, otherwise it might end up too quickly and get garbage collected, as shown in the example code:

Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                Thread.sleep(1000);
            }
        } catch (InterruptedException ignored) {
            //
        }
    }
});

Upvotes: 8

phihag
phihag

Reputation: 288070

If the (Runnable) Car instance exits shortly after being started, the memory allocated for the thread is freed. If the rate of freeing memory is greater than the thread spawning rate, you'll never get an OutOfMemoryError. You can prevent that by making Car run for a long time, for example:

class Car implements Runnable {
   public void run() {
      Thread.sleep(10000000);
   }
}

Upvotes: 1

Related Questions