Marthin
Marthin

Reputation: 6543

difference between Java atomic integer and C# Interlocked.Increment method

Im just wondering, is there a difference between how you increment a static variable in Java and C# in an threaded enviroment?

In Java you use atomic int:s to make this operation and in C# you use Interlocked.Incement(ref yourVar)

I by this dont mean the code you write but how it is actually locks the memory and does the actual increment.

Upvotes: 13

Views: 6615

Answers (2)

crypted
crypted

Reputation: 10306

Interlocked operation doest not lock memory, it rather emits LOCK prefix to the instruction depending on the operation. That cause processor to assert bus lock so only instruction is executed once. You can further look at the following article

Since the link is no longer working here is the archived version
https://web.archive.org/web/20140325112655/http://lists.canonical.org/pipermail/kragen-tol/1999-August/000457.html

Upvotes: 9

Stephen C
Stephen C

Reputation: 719189

In the case of Java - the "how it works" depends on the instruction set of the execution platform. I was reading (earlier today while waiting for an interminable OS upgrade to finish) that on x86 AtomicXxx classes are implemented using a Compare and Swap (CAS) instruction.

Upvotes: 2

Related Questions