Junior — Middle
How does an object behave when it is modified simultaneously from multiple threads?
sobes.tech AI
Answer from AI
When an object is modified simultaneously from multiple threads without proper synchronization, it leads to a race condition. As a result:
- Data can become inconsistent or corrupted.
- Program behavior becomes unpredictable and difficult to debug.
- Errors such as lost updates, partial changes, or crashes may occur.
To prevent such issues, synchronization mechanisms should be used, for example:
synchronizedblocks or methods in Java/Kotlin.- Classes from
java.util.concurrent, such asReentrantLock. - Use of thread-safe collections and atomic operations.
Example of using synchronized in Kotlin:
class Counter {
private var count = 0
@Synchronized
fun increment() {
count++
}
fun getCount(): Int = count
}
Without synchronization, multiple threads can read and write to count simultaneously, leading to incorrect results.