Siva Sai kiran
Siva Sai kiran

Reputation: 67

How to avoid thread interference while updating database in multithreading

I have a java class ,which has two methods .These methods will be called one after the other. These methods are making rest calls to different services. After getting data from rest call ,i'm updating multiple tables and some of the tables will be updated by both methods. My task is to implement multithreading to run both methods simultaneously but avoid threads to override data while they are updating the same table. What are the different ways to do it and how can i do it effectively in java8.

Upvotes: 2

Views: 88

Answers (2)

Ilam
Ilam

Reputation: 328

It is better to view this problem from data integrity perspective rather than threads. Because your application could run in a cluster (if not now, maybe later). There could be other users updating same table, from other applications.

The solution depends on the level of contention(the number of threads trying to update the same database table).

If there is high contention, use pessimistic locking. Refer pessimistic locking

If there is low contention, use optimistic locking. Refer optimistic locking

Upvotes: 0

Lam Le
Lam Le

Reputation: 829

To avoid race condition, you should wait for both thread collect all data from 2 rest calls then do the database modification, like example:

ExecutorService es = Executors.newFixedThreadPool(2);
List<Callable<Object>> todo = new ArrayList<Callable<Object>>();

todo.add(Executors.callable(new TaskCallRest1())); 
todo.add(Executors.callable(new TaskCallRest2())); 

List<Future<Object>> answers = es.invokeAll(todo);

For database synchronization, you can use optimistic lock to prevent multiple update. Optimistic lock simple is version of your record and the query look like:

update A set B = b, version = 2 where version = 1; 

Only one thread can execute successful this query due to database ACID. If you use Hibernate for persistence layer, you can looking for Hibernate Versioning

Upvotes: 1

Related Questions