Senior
What is the main cause of incorrect code behavior Objects' immutability is violated Interrupt status is not handled Performance degradation due to locking Lock object conflicts lead to deadlock situations Excessive resource synchronization Uninitialized object states import java.util.concurrent.*; class Competition { private final Object lock = new Object(); public void syncMethodA(Competition competitor) { synchronized (lock) { try { Thread.sleep(100); } catch (InterruptedException e) {} competitor.syncMethodB(this); } } public void syncMethodB(Competition competitor) { synchronized (lock) { try { Thread.sleep(100); } catch (InterruptedException e) {} competitor.syncMethodA(this); } } } public class FitnessApp { public static void main(String[] args) { Competition comp1 = new Competition(); Competition comp2 = new Competition(); Thread t1 = new Thread(() -> comp1.syncMethodA(comp2)); Thread t2 = new Thread(() -> comp2.syncMethodB(comp1)); t1.start(); t2.start(); } }
sobes.tech AI
Answer from AI
The main cause of incorrect code behavior is object lock conflicts leading to a deadlock situation.
In this example, two Competition objects try to acquire each other's locks:
comp1.syncMethodA(comp2)acquirescomp1.lockand tries to callcomp2.syncMethodB(this), which attempts to acquirecomp2.lock.- Simultaneously,
comp2.syncMethodB(comp1)acquirescomp2.lockand tries to callcomp1.syncMethodA(this), which attempts to acquirecomp1.lock.
As a result, both threads wait for the lock held by the other thread — a classic deadlock.
To avoid this situation, you should:
- Use the same lock object for all synchronized methods.
- Avoid nested calls that require acquiring multiple locks.
- Apply timeouts or other mechanisms to prevent deadlocks.
An example fix is to use a single shared lock for all objects or redesign the logic to avoid cross-calls with locks.