async insertion to database in a java webservice

116 views Asked by At

My java web service performs lots of mathematical operations and finally finds a result to return. Before return the result I want to insert some data to DB about mathematical operations. You think like that I want to log something.

But I have very busy server where the database is located. So logging takes too much time. But in fact math operations doesn't take too much time. And my webservices always wait for finishing logging to DB.

My web services pseudocode is like that :

WebService {  

math operations..     
math operations..    
math operations..  

    insertion to db  --> taking to much time

   return result 
}

So I want to instert logs to DB asnychoronously. Can you give me advice for that? It can be library or framework which perform multithreading and asnyc queue inside.

PS: I dont want to use Log4j and nested webservices. And I don't want to handle threads manually.

1

There are 1 answers

2
bobah On

Create a thread with Executors.newSingleThreadExecutor() (it does not count as manual thread management). And instead of writing

dao.persist(item);

write

executor.submit(new Runnable() {
    @Override public void run() { dao.persist(item); }
});