简体   繁体   中英

Multi Threaded Application with (Spring) ThreadPoolTaskExecutor

I need to implement Multi Threaded background process. My project is spring , hibernate based I tried with below code which uses org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor to perform the below background operation in multi threaded manner.

I need to know

  1. If I use Spring ThreadPoolTaskExecutor is this multi threaded?
  2. Will there be overlapping issues like multiple threads acqure the same user object ?
  3. If "YES" Should I need to use synchronize the method upgradeUserInBackground() to avoid such a situations ? Alternative solution ?

     public class UserUpdateProcessor implements InitializingBean { private ThreadPoolTaskExecutor executor; public void afterPropertiesSet() throws Exception { executor.execute(new UserBackgorundRunner ()); } } private class UserBackgorundRunner extends Thread { public UserBackgorundRunner() { this.setDaemon(true); this.setPriority(MIN_PRIORITY); } 

    public void run() {

      List<User> users = getUserList();; for (User user : users) { try { upgradeUserInBackground(user); } catch (Exception e) { LOGGER.warn("Fail to upgrade user"); } } } 
  1. Yes, it is multi threaded, all submitted tasks will be executed at the same time. Spring takes care of thread starvation as well so there will be parallel execution always until you try some hacks.

  2. Yes, there may be overlapping issues like multiple threads acqure the same user object.

  3. For your scenario i would advice you to use Spring Batch FMK and configure/hack it for not saving any data in database. It will give you concurrency, speed, reliability and solution of overlapping objects using tasklet "scope".

If you use synchronization in threads, it is considered to be a bad design, rethink your problem.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM