使用Executors.newScheduledThreadPool执行程序服务会导致Java中的内存不足错误

时间:2018-08-21 13:27:49

标签: threadpool

我有一个场景,我们需要以10秒的频率发布1小时内5000多个设备的数据。我正在使用512 MB的内存,此过程似乎在15分钟内崩溃。

我正在使用executor.scheduleAtFixedRate(runnable,0,10,TimeUnit.SECONDS)将其作为任务进行计划

执行者内部使用的LinkedBlockingQueue看起来比线程能够完成每个可运行任务的速率非常高,并且队列中的任务对象变得繁重并且用尽了内存。每个对象大约2MB,由于架构限制,我们无法减少该对象。

我看到LinkedBlockingQueue的容量为2147483647,但是当队列数仅为131000时,就会发生内存泄漏。

我们如何处理这种情况?另外,为什么队列中堆积了那么多任务?计划执行程序是否应该仅创建5000个任务(用于5000个设备)并每次都以10秒的延迟运行同一任务?

请帮助我们了解如何处理此问题? 有更好的方法吗?

代码示例:

public void publishData(){

    for(int device=0 ; device <5000; device++){

    // 5000 devices will be scheduled to publish data every 10 secs for 1 hour after which we will cancel this future
        // 1 device posts 3600 times in 1 hr and hence for 5000 devices there should be 18000000 publishes
        // these are too many publishes for the internal LinkedBlockingQueue to handle as each object in the queue is heavy and consumes memory and hence eats up all the allotted memory

        final Future<?> future = executor.scheduleAtFixedRate(runnable, 0, 10, TimeUnit.SECONDS);
    }
}

public void run(){

    ExistingPublishAPI api = new ExistingPublishAPI();
    api.publish(device_data);
}

ExistingPublishAPI-是我们项目中的现有api,用于发布数据。 device_data-需要发布的数据,基本上每个对象的大小为2MB

0 个答案:

没有答案