Saturday, 27 September 2008

Super-Power Synchronisation in Java and C#: Say Arrivederci to the Ornamental Garden Problem and Buonasera Deadlock!

In Java you would use a synchronised block. In C#, the syntactic shortcut lock does the same thing.

lock(x), where x is a reference type, is equivalent to

System.Threading.Monitor.Enter(x)
try {
...
} finally {
System.Threading.Monitor.Exit(x);
}

except that x is only evaluated once. Locking avoids problems like the ornamental garden problem. C#'s System.Threading namespace has stuff for COM interoperability which Java doesn't have e.g. the the System.Threading.ApartmentType to determine if an apartment is STA or MTA.

No comments: