Alipay+ DocsAlipay+ Docs

ThreadPoolService

Call the ThreadPoolService SPI to implement and manage your own thread pool. If you do not provide an implementation, the SDK will use its default thread pool.

Method signature

copy
public interface ThreadPoolService {

    void execute(Runnable task, String threadName);

    void shutdown();
}

Request parameters

Item

Type

Parameters

Description

Required

execute()

function

Runnable task

String threadName

Submits a task for asynchronous execution.

Required

shutdown()

function

/

Shutdowns the thread pool and terminates all the threads in the thread pool.

Required

Response parameters

N/A

Sample

copy
public class ThreadPoolServiceImpl implements ThreadPoolService {

    private final ExecutorService serialExecutor;
    private final ExecutorService parallelExecutor;

    public ThreadPoolServiceImpl() {
        this.serialExecutor = Executors.newSingleThreadExecutor(new NamedThreadFactory("Tap-SerialExecutor"));

        this.parallelExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new NamedThreadFactory("Tap-ParallelExecutor"));
    }

    @Override
    public void executeSerially(Runnable task, String threadName) {
        if (serialExecutor == null) return;
        serialExecutor.execute(new NamedRunnable(task, threadName));

    }

    @Override
    public void execute(Runnable task, String threadName) {
        if (parallelExecutor == null) return;
        parallelExecutor.execute(new NamedRunnable(task, threadName));

    }
    @Override
        public void shutdown(){
            if (parallelExecutor != null){
                parallelExecutor.shutdown();
            }
        }

    private static class NamedRunnable implements Runnable {
        private final Runnable task;
        private final String threadName;

        public NamedRunnable(Runnable task, String threadName) {
            this.task = task;
            this.threadName = threadName;
        }

        @Override
        public void run() {
            if (!TextUtils.isEmpty(threadName)) {
                Thread.currentThread().setName(threadName);
            }
            task.run();
        }
            
    }

    private static class NamedThreadFactory implements ThreadFactory {
        private final String baseName;
        private int counter = 0;

        public NamedThreadFactory(String baseName) {
            this.baseName = baseName;
        }

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, baseName + "-thread-" + counter++);
        }
    }


}