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?

1
  • 1
    Check this article for gentle introduction what you could do with Spring's @Async annotation. Commented Apr 21, 2017 at 7:33

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

But he will also need the ThreadLocals 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 could you please provide your answer with Thread pool and ThreadLocals
@RanPaun See this answer for the ThreadLocals - depending on the code base you may or may not need them. About the ThreadPool: you specify @Async("customThreadPoolExecutor") and define the configuration of the customTHreadPoolExecutor.
One other thing for the ThreadPool: you can specify the default executor for these @Async tasks: <task:annotation-driven executor="myExecutor" />. Credit goes to this answer: stackoverflow.com/a/19144306/25429
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.