0

I have customDao as below in my springboot app,

@Component
public class CustomDao {

    private final JdbcTemplate jdbcTemplate

    @Autowired
    private PlatformTransactionManager transactionManager;

    def logger = LoggerFactory.getLogger(this.class);
    @Autowired
    public CustomDao(JdbcTemplate template) {
        this.jdbcTemplate = template
    }


    public insertRecord(sql,params){
        //insert
    }

    public updateRecord(sql,params){
       //update
    }
}

And am trying to make only update operation asynchronously in a new Thread, I havent worked much on Threads, can someone please help me with this?

OTUser
  • 3,788
  • 19
  • 69
  • 127
  • 1
    Check [this article](http://www.baeldung.com/spring-async) for gentle introduction what you could do with Spring's `@Async` annotation. – zloster Apr 21 '17 at 07:33

2 Answers2

1

You may modify your updateRecord method to this:

public void updateRecord(sql, params) {
    Thread t = new Thread() {
        //Your code to update here
    }
    t.start();
}

Thread t = new Thread() {...} will create a new thread to do the specified work and t.start() will run the thread in the background.

Deepesh Choudhary
  • 660
  • 1
  • 8
  • 17
  • 1
    But he will also need the `ThreadLocal`s from the original thread. Spring stores there some important stuff. Also it is better to use some form of thread pool. The current approach will quickly become "expensive". – zloster Apr 21 '17 at 07:30
  • @zloster could you please provide your answer with Thread pool and ThreadLocals – OTUser Apr 21 '17 at 07:53
  • @RanPaun See [this answer](http://stackoverflow.com/a/33337838/25429) for the `ThreadLocal`s - depending on the code base you may or may not need them. About the ThreadPool: you specify [`@Async("customThreadPoolExecutor")`](http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#scheduling-annotation-support-qualification) and [define the configuration](http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#scheduling-task-namespace-executor) of the customTHreadPoolExecutor. – zloster Apr 21 '17 at 16:12
  • One other thing for the ThreadPool: you can specify the default executor for these `@Async` tasks: ``. Credit goes to this answer: http://stackoverflow.com/a/19144306/25429 – zloster Apr 21 '17 at 16:20
1

You should use @Async to handle asynchronous tasks into Spring. You can find an example here.