生成OutOfMemory错误的时间类

时间:2014-05-24 10:45:02

标签: java timer out-of-memory

我正在使用Time类并创建20 tps,但是我收到了以下错误。

 Exception in thread "pool-1-thread-9" java.lang.OutOfMemoryError: unable to create new native thread
        at java.lang.Thread.start0(Native Method)
        at java.lang.Thread.start(Thread.java:597)
        at java.util.Timer.<init>(Timer.java:137)
        at java.util.Timer.<init>(Timer.java:106)
        at mcarbon.ucip.SheduleInMemRemove.<init>(SheduleInMemRemove.java:22)
        at mcarbon.ucip.XML_RPC_UCIP_DEBIT_CREDIT.run(XML_RPC_UCIP_DEBIT_CREDIT.java:229)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
        at java.lang.Thread.run(Thread.java:619)

代码: -

class SheduleInMemRemove{
            Timer timer;
        Config cfg;
          String key;

           public SheduleInMemRemove(String key,int seconds,Config cfg,String MSG,String IP,String PORT,boolean isResponse)
           {
                this.key=key;
                this.cfg=cfg;
                 LoggerWR.logger.info("[IN URL] [inside SheduleInMemRemove constructor][going to sleep to IN memory key["+key+"] [wake up after "+seconds+" seconds] [MSG]["+MSG+"] [isResponse]["+isResponse+"]");
                cfg.addInMem(key,IP,PORT,MSG,isResponse);
                //LoggerWR.logger.info("[IN URL] [Going to shedule]");
                timer = new Timer();
                timer.schedule(new WakeUpInTask(),seconds*1000);
                //LoggerWR.logger.info("[IN URL] [Done]");
           }
                class WakeUpInTask extends TimerTask
                {
                public void run() {
                //System.out.format("Time's up!%n");
                LoggerWR.logger.info("[IN URL] [Inside the SheduleInMemRemove class going to remove the key]["+key+"] ["+cfg.removeInMem(key)+"]");
                 //cfg.removeInMem(key);
                    timer.cancel(); //Terminate the timer thread
                }
        }
    }

请帮助

1 个答案:

答案 0 :(得分:0)

每个新线程都需要一大块内存才能用于其调用堆栈。显然,你启动的线程比你的内存更多。

如果您要创建大量计时器,则应考虑改为使用a ScheduledExecutorService