Junior — Middle
Have you had experience working with situations where data in the system was inconsistent under the conditions of simultaneous access by multiple users?
sobes.tech AI
Answer from AI
Yes, in conditions of simultaneous access by multiple users, issues with data inconsistency often arise. For example, if two users try to update the same record in a database at the same time, without proper synchronization, data loss or conflicts can occur.
To address such situations, Java uses:
- Locking mechanisms (synchronized, ReentrantLock) to control access to shared resources.
- Transactions with an isolation level that ensures data consistency.
- Optimistic and pessimistic locking strategies.
An example of using synchronized to protect a shared resource:
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
This approach prevents multiple threads from changing the variable count simultaneously, maintaining data consistency.