Hibernate / EclipseLink Interview questions
When should you use pessimistic locking instead of optimistic locking?
Optimistic locking assumes conflicts are rare and only detects them at commit time via a version mismatch; pessimistic locking prevents conflicts up front by acquiring an actual database row lock (typically via SELECT ... FOR UPDATE) the moment the data is read for update.
Employee emp = em.find(Employee.class, id, LockModeType.PESSIMISTIC_WRITE); emp.setSalary(emp.getSalary().add(bonus));
Pessimistic locking is the right call when a conflict is likely (high contention on the same rows) or when the cost of a failed, retried operation is too high to accept, such as a financial transaction that shouldn't be attempted twice. It comes at the cost of holding a real database lock for the duration of the transaction, which reduces concurrency and can lead to lock contention or, in worse cases, deadlocks if not carefully scoped.
Optimistic locking remains the better default for most applications: it scales better under normal, low-contention conditions and only pays a cost (an exception and a retry) exactly when a real conflict actually happens, rather than serializing access preemptively for every read.
More Related questions...