如何通过生成线程来命中java.lang.OutOfMemoryError?

时间:2011-07-24 10:01:00

标签: java multithreading out-of-memory

我遇到了这个blog site,其中作者在机器抛出java.lang.OutOfMemoryError之前测试了最大线程数。但是,在我的下面的测试代码中,尽管产生了任意大的线程,但我无法遇到错误。

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

3 个答案:

答案 0 :(得分:8)

尝试在线程内部休眠,否则可能会过快地收集垃圾,如example code所示:

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

答案 1 :(得分:1)

如果(Runnable)Car实例在启动后不久退出,则释放为该线程分配的内存。如果释放内存的速率大于线程产生速率,则永远不会得到OutOfMemoryError。您可以通过让Car长时间运行来阻止这种情况,例如:

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

答案 2 :(得分:1)

另请参阅JavaSpecialists Newsletter#149中提到的同一问题 http://www.javaspecialists.eu/archive/Issue149.html

您可以运行以下一小段代码来查找可以在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();
    }
  }
}