Reputation: 3592
The following code is supposed to be vulnerable to TOCTOU attack:
public Period(final Date start, final Date end) {
if (start.compare(end) > 0) {
throw new IllegalArgumentException("");
}
this.start = start;
this.end = end; // Class period has 2 private final member
// variables Date start & end.
}
What I fail to understand is that how will this race condition work? Say there are 2 threads T1 and T2 where T1 has a valid set of arguments and should pass the check and T2 is a hacker who wants to set invalid values in the class.
If 2 threads are racing and this piece of code is our critical section, then say T1 runs passes the check and sleeps. Now when T2 will start running won't it go through the check again (and fail)??
Upvotes: 3
Views: 2431
Reputation: 328775
The problem is that Date
is mutable, so another thread could change the end date: end.setTime(0);
after you have checked that start.after(end)
(easier way to write your condition).
So it would look like:
start.after(end)
=> returns false, all looks goodend.setTime(0);
=> sneaky Thread 2 changes the datethis.start = start; this.end = end; //boom
=> your class invariant is not valid anymoreUpvotes: 9