NikhilP
NikhilP

Reputation: 1703

how to make thread wait until another thread has completed that method execution

Although this question seems basic, my scenario is quite different from other posts @stackoverflow. I am using spring with JPA & jersey(REST) implementation. Whenever I hit 2 requests concurrently from curl to my Java REST method in order to update database resources, first request gets executed successfully but 2nd request gets failed with optimistic lock exception:

javax.persistence.OptimisticLockException: Exception [EclipseLink-5006] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.OptimisticLockException Exception Description: The object cannot be updated because it has changed or been deleted since it was last read.

I have tried putting the updated code in synchronized block but it didn't worked.

I have also tried declaring that rest method synchronized but didn't work.

Now I want my method to be executed by first request and want second request to wait until first request completes it execution.

I had achieved this using static variable but don't want to use static variable due to code standards.

Can someone give efficient solution for this?

Upvotes: 0

Views: 309

Answers (1)

NikhilP
NikhilP

Reputation: 1703

using synchronization before DB call will help.

1)using Synchronized keyword

synchronized(this){
//process
}

2)other option is to use synchronized before method name

synchronized void <method(){
//process
}

Upvotes: 1

Related Questions