I am trying to use concurrent mechanism in my Spring based web application. so that I have used the below method to use thread concept to get the employee details. but I have failed with Null pointer exception due to spring context is null on threads.
I have used the below code:
ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
threadPool.setCorePoolSize(10);
threadPool.initialize();
ExecutorServiceAdapter adapter = new ExecutorServiceAdapter(threadPool);
List<Callable<Employee>> tasks = new ArrayList<Callable<Employee>>();
for (int i = 0; i < employeeArr.length; i++) {
final int value = i;
tasks.add(new Callable<Employee>() {
public Employee call() throws Exception {
return empService.getEmployeeDetails(employeeArr[value], finalFromDate);
}
});
}
try {
List<Future<Employee>> result = adapter.invokeAll(tasks);
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i).get());
}
} catch (ExecutionException ex) {
ex.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
In the "empService.getEmployeeDetails" method, I am referring the Spring context by using below code:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Collection<GrantedAuthority> authorities = auth.getAuthorities();
But I am getting null pointer exception when accessing the spring context.
could anyone please help me on this?
You can take advantage of org.springframework.security.task.DelegatingSecurityContextAsyncTaskExecutor
. Try something like this:
ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
threadPool.setCorePoolSize(10);
threadPool.initialize();
TaskExecutor taskExecutor = new DelegatingSecurityContextAsyncTaskExecutor(threadPool);
ExecutorServiceAdapter adapter = new ExecutorServiceAdapter(taskExecutor);
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.