Spring为每个客户端创建异步操作的线程池

时间:2015-01-07 02:03:01

标签: java multithreading spring asynchronous threadpool

我希望在从spring控制器向用户发送响应后异步执行某些操作。基本上我需要一个线程池,每个客户端不能有多个线程用于异步操作。每个线程都有一个单独的数据库连接 我创造了这样的东西。但在这种情况下,每个用户可以拥有多个线程。如何在已经为当前用户运行的线程上执行任务?

public class DatabaseAsyncTaskManager {
    private static DatabaseAsyncTaskManager instance;
    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(), 1000,
            100000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

    private WeakHashMap<Thread, DatabaseManager> databaseManagers =
            new WeakHashMap<Thread, DatabaseManager>();

    private class ThreadFactoryImpl implements ThreadFactory {
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            databaseManagers.put(thread, new DatabaseManager());
            return thread;
        }
    }

    public synchronized static DatabaseAsyncTaskManager getInstance() {
        if(instance == null){
            instance = new DatabaseAsyncTaskManager();
        }

        return instance;
    }

    private DatabaseAsyncTaskManager() {
        ThreadFactory threadFactory = new ThreadFactoryImpl();
        threadPoolExecutor.setThreadFactory(threadFactory);
        lowPriorityExecutor.setThreadFactory(threadFactory);
    }

    private void executeOnExecutor(Executor executor, final Task task) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                Thread thread = Thread.currentThread();
                DatabaseManager databaseManager = databaseManagers.get(thread);
                task.run(databaseManager);
            }
        });
    }

    public void executeAsyncTask(final Task task) {
        executeOnExecutor(threadPoolExecutor, task);
    }
}

0 个答案:

没有答案