Sobes.tech
Junior — Middle

Can you give an example of a situation in Java where pessimistic locking is used to prevent conflicts when accessing data?

sobes.tech AI

Answer from AI

Pessimistic locking in Java is often used when it is necessary to guarantee that data will not be modified by other threads during the execution of a critical operation. For example, when working with a database through JPA/Hibernate, you can use the lock() method with the PESSIMISTIC_WRITE lock type to prevent concurrent modification of the same record:

EntityManager em = ...;
EntityTransaction tx = em.getTransaction();
tx.begin();

// Obtain an object with a write lock
MyEntity entity = em.find(MyEntity.class, id, LockModeType.PESSIMISTIC_WRITE);

// Make changes
entity.setValue(newValue);

// Save changes
em.persist(entity);
tx.commit();

In this example, until the transaction is completed, other transactions attempting to acquire a lock on the same record will wait, preventing conflicts and ensuring data integrity.