Search code examples
javamultithreadingthread-safetyvolatile

Possible race condition in this java code?


class Employee {
   transient Department = new Department();
}   
class Department {
   boolean isClosed;
}

by default isClosed is false, some point in my logic its changed to true (Department.isClosed = true) but later in process its changed back to false ==> No logic to explicitly change this.

Based on my understanding, I suspect that this is happening due to Race Condition where different thread have modified this flag or one thread is not getting updated view of data.

Is there anyway to prove this understanding? or possibly any other suspects?

Please note, Its difficult(total 8-10 hours of retry and processing) to reproduce this issue as we face on production very rarely.


Solution

  • You need to make isClosed volatile if it is modified and then accessed from different threads. In the other case, a different thread may see a stale value even after seeing a more up-to-date value.