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

Method

Item

Type

Description

Required

execute

task

Runnable

The task to execute asynchronously.

Yes

threadName

String

The name to assign to the thread.

Yes

shutdown

N/A

N/A

Shuts down the thread pool and terminates all the threads in the thread pool.

Yes

Response parameters

N/A

Sample

The following example shows a minimal implementation using a cached thread pool. For production use, consider using a bounded thread pool to limit the maximum number of concurrent threads.

copy
public class CustomThreadPool implements ThreadPoolService {

    private final ExecutorService executor = Executors.newCachedThreadPool();

    @Override
    public void execute(Runnable task, String threadName) {
        executor.execute(() -> {
            if (threadName != null && !threadName.isEmpty()) {
                Thread.currentThread().setName(threadName);
            }
            task.run();
        });
    }

    @Override
    public void shutdown() {
        executor.shutdown();
    }
}