2

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.

1
  • At present your second process "wins". You should modify the first process so that it doesn't update that value, then you can run them concurrently. Commented Feb 13, 2023 at 3:40

2 Answers 2

1

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

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

1 Comment

thank you,my concern is not about the restcalls but updating the database,can i use some kind of synchronization to let only one thread update the db at a time.
0

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

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.