Java异步执行增加CPU 100%

时间:2015-07-16 10:00:10

标签: java spring

简介:

我开发了一个可以接受Prop数量的类,并行执行它们并等待特定时间的结果。如果某些任务未能在给定超时时间内完成,则会中断整个执行并仅返回可用结果。

问题:

一切正常,但一段时间后CPU使用率增加到100%,应用程序显然无法响应。

您能否尝试帮助我找到问题或建议更好的解决方案,以实现相同的目标?

代码:

TaskService.java

UserControl

AsynchronousTaskService.java

MyProp

ThreadExecutorFactory.java

Tasks

Task.java

public abstract class TaskService {

    private static final org.slf4j.Logger InfoLogger = LoggerFactory.getLogger("InfoLogger");
    private static final org.slf4j.Logger ErrorLogger = LoggerFactory.getLogger("ErrorLogger");

    @Autowired
    private TimeLimiter timeLimiter;


    public List<TaskResult> execute(TaskType taskType, TimeUnit timeUnit, long timeout, final Task... tasks){

        final List<TaskResult> taskResultsStorage = new ArrayList<>();
        try {
            timeLimiter.callWithTimeout(new Callable<List<TaskResult>>() {
                @Override
                public List<TaskResult> call() throws Exception {
                    return run(taskResultsStorage, tasks);
                }
            }, timeout, timeUnit, true);

        } catch (UncheckedTimeoutException e) {
            String errorMsg = String.format("Time out of [%s] [%s] has been exceeded for task type:[%s]", timeout, timeUnit.name(), taskType.name());
            ErrorLogger.error(errorMsg, e);
        } catch (Exception e) {
            String errorMsg = String.format("Unexpected error for task type:[%s]", taskType.name());
            ErrorLogger.error(errorMsg, e);
        }

        return taskResultsStorage;
    }



    protected abstract List<TaskResult> run(List<TaskResult> taskResults,Task... tasks) throws ExecutionException, InterruptedException;

}

TaskResult.java

public class AsynchronousTaskService extends TaskService {


    private CompletionService<TaskResult> completionService;

    public AsynchronousTaskService(ThreadExecutorFactory threadExecutorFactory){
        this.completionService = new ExecutorCompletionService<TaskResult>(threadExecutorFactory.getExecutor());
    }


    @Override
    protected List<TaskResult> run(List<TaskResult> resultStorage, Task... tasks) throws ExecutionException, InterruptedException {

        List<Future<TaskResult>> futureResults = executeTask(tasks);
        awaitForResults(futureResults, resultStorage);
        return resultStorage;
    }


    private List<Future<TaskResult>> executeTask(Task... tasks){

        List<Future<TaskResult>> futureTaskResults = new ArrayList<>();
        if(tasks!=null) {
            for (Task task : tasks) {
                if (task != null) {
                    futureTaskResults.add(completionService.submit(task));
                }
            }
        }
        return futureTaskResults;
    }

    private void awaitForResults(List<Future<TaskResult>> futureResults, List<TaskResult> resultStorage) throws ExecutionException, InterruptedException {

        int submittedTasks = futureResults.size();
        int taskCompleted = 0;
        if(futureResults != null){
            while(taskCompleted < submittedTasks){
                Iterator<Future<TaskResult>> it = futureResults.iterator();
                while(it.hasNext()){
                    Future<TaskResult> processingTask = it.next();
                    if(processingTask.isDone()){
                        TaskResult taskResult = processingTask.get();
                        resultStorage.add(taskResult);
                        it.remove();
                        taskCompleted++;
                    }
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您的方法awaitForResults包含一个繁忙的循环:

while(taskCompleted < submittedTasks){
    ...
    while(it.hasNext()){

这会像疯了一样吃CPU,并阻碍实际的线程。您应该像实例一样添加睡眠

 Thread.sleep(1000);

这是Quick&amp; Dirty但有助于解决100%的cpu问题。或者,但更多的努力是实现一些信令机制,以便循环等待来自其中一个完成任务的信号。

像其他人建议的那样,如果它们全部受cpu约束,那么拥有100个线程可能没有意义,但我怀疑这确实是你的问题。