Sobes.tech
Junior — Middle

Kas saaksid anda näite Java olukorrast, kus kasutatakse pessimisti blokki, et vältida konfliktide tekkimist andmetele juurdepääsul?

sobes.tech AI

Vastus AI-lt

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

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

// Get object with 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.