3

I use Spring Data JPA with Hibernate as persistence provider over PostgreSQL. I'm trying to provide pessimistic locking:

public interface MediaRepository extends JpaRepository<Media, Long>, MediaRepositoryCustom {
Long countByCreatedBy(User creator);

@Query("select m from Media m where m.id = ?1")
@Lock(LockModeType.PESSIMISTIC_WRITE)
Media findOneAndLock(Long id);
}

I try to call findOneAndLock from 2 threads. I expect that if Thread A locks object, Thread B should wait until the lock is released. But instead Thread B throws org.springframework.orm.ObjectOptimisticLockingFailureException.

I'm sure that both threads performs select for update (2 such records in database log).

1 Answer 1

1

The default behavior is to not wait. You need to specify the wait period in the persistence.xml

<properties>
   <property name="javax.persistence.lock.timeout" value="1000"/>
</properties>
Sign up to request clarification or add additional context in comments.

7 Comments

Whats the value? And the second thread will only wait for the configured time and NOT indefinitely.
10000. Again, I catch org.springframework.orm.ObjectOptimisticLockingFailureException.
Does this exception occur immediately or after 10 seconds?
It occurs immediately and it's stack trace includes call to findOneAndLock
Yes because its a hint and may not be applied always. read here.
|

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.