Mostly technical stuff with some interesting moments of life

C# and Java Operators Thread Safety

No comments
Java and C# both have compound assignment operators and the increment/decrement operators. For example see for a list of C# operators and for the Java version.

It seems these two step operations, i.e. x op= y, x++, x--, ++x, and --x, are NOT thread safe. It makes sense as these operations require reading the current value of the given variable and then updating it with the computed value. It is possible for threads to interleave between these operations resulting erroneous final values.

There are many ways to guarantee the atomicity in such cases including synchronized blocks, atomic data types such as Java AtomicInteger, and interlocked operations like in C#.

Here are some links that may help,

C# interlocked methods:

Java atomic classes

C# library to do threading similar to OpenMP like constructs

A Java alternative OpenMP like parallel constructs

No comments :

Post a Comment