May a correct program be incorrectly synchronized?
-
27-06-2021 - |
Question
In answer of Does a correctly synchronized program still allow data race?(Part I), it gives us a good example: all executions of a program appear to be sequentially consistent, but it still has data race. It tells us why another direction of following conclusion in JLS is not true:
If a program has no data races, then all executions of the program will appear to be sequentially consistent.
Now take a look at another conclucsion in JLS:
A program is correctly synchronized if and only if all sequentially consistent executions are free of data races.
According to this conclusion,above example is not correctly synchronized, so may a correct program be incorrectly synchronized?
Solution
You would probably need to define first what a correct program is (not easy). JCiP proposes (in a different context):
a program is correct if it conforms to its specifications.
Using that definition, the example provided is correct. However, it is not correctly synchronized (there is a data race on hash
).
==> a correct program may be incorrectly synchronized, as proved by that example.
OTHER TIPS
While this doesn't appear to answer the OP's question, I am keeping it for the comments.
You can get a number of race conditions using synchronized collections. e.g.
Vector<Integer> vector = ...
vector.add(1);
vector.set(0, 1 + vector.get(0));
Each method is synchronized and yet there is a race condition. This is because you can have threads T1 and T2 doing.
T1: int tmp1 = vector.get(0);
T2: int tmp2 = vector.get(0);
T1: vector.set(0, 1 + tmp1);
T2: vector.set(0, 1 + tmp2);
In this case tmp1 == tmp2 which is not normally the case.
To synchronize this correctly you would do the following to ensure you hold the lock the whole time.
synchronized(vector) {
vector.set(0, 1 + vector.get(0));
}