I want to execute some operations asynchronously, after sending a response to user from the spring controller. Basically I need a thread pool, where each client can't have more then one thread for async operations. Each thread has a separate database connection. I created something like this. But each user can have more then one thread in this case. How can I execute the task on a thread which is already running for the current user?
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);
}
}