ExecutorService which runs tasks in calling thread?

ぐ巨炮叔叔 提交于 2019-12-01 20:56:24

The only existing implementation I could find is SynchronousExecutorService - unfortunately buried somewhere in library.

Pasting source code (without comments) here for future reference:

package org.apache.camel.util.concurrent;

import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.TimeUnit;

public class SynchronousExecutorService extends AbstractExecutorService {

    private volatile boolean shutdown;

    public void shutdown() {
        shutdown = true;
    }

    public List<Runnable> shutdownNow() {
        return null;
    }

    public boolean isShutdown() {
        return shutdown;
    }

    public boolean isTerminated() {
        return shutdown;
    }

    public boolean awaitTermination(long time, TimeUnit unit) throws InterruptedException {
        return true;
    }

    public void execute(Runnable runnable) {
        runnable.run();
    }

}

You may use Guava com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor() which does exactly what you want: https://github.com/google/guava/blob/0434c5199c83c3f43b8b6a86c62e121d518fe7d0/guava/src/com/google/common/util/concurrent/MoreExecutors.java#L267

EDIT: The method has been renamed to com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService() https://github.com/google/guava/blob/f67ab864bde63fa6602b5688de0440957ffeaa2e/guava/src/com/google/common/util/concurrent/MoreExecutors.java#L369

have you looked at java.util.concurrent.ThreadPoolExecutor?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!