<!DOCTYPE qhelp PUBLIC
  "-//Semmle//qhelp//EN"
  "qhelp.dtd">
<qhelp>

<overview>
<p>
Often it is necessary to check the state of a resource before using it.
If the resource is accessed concurrently, then the check and the use
need to be performed atomically, otherwise the state of the resource may change between the check
and the use. This can lead to a "time-of-check/time-of-use" (TOCTOU) race condition.
</p>

<p>
In Java, classes may present state inspection methods and operation methods which are synchronized. 
This prevents multiple threads from executing those methods simultaneously, but it does not prevent a
state change in between separate method invocations.
</p>
</overview>

<recommendation>
<p>When calling a series of methods which require a consistent view of an object, make sure to synchronize
on a monitor that will prevent any other access to the object during your operations.
</p>
<p>
If the class that you are using has a well-designed interface, then synchronizing on the object itself will 
prevent its state being changed inappropriately.
</p>
</recommendation>

<example>

<p>
The following example shows a resource which has a readiness state, and an action that is only valid if the
resource is ready.
</p>

<p>
In the bad case, the  caller checks the readiness state and then acts, but does not synchronize around the
two calls, so the readiness state may be changed by another thread.
</p>

<p>
In the good case, the caller jointly synchronizes the check and the use on the resource, so no other thread
can modify the state before the use.
</p>

<sample src="TOCTOURace.java" />

</example>
<references>
</references>
</qhelp>
