John Goering
John Goering

Reputation: 39040

Are there any differences between Java's "synchronized" and C#'s "lock"?

Do these two keywords have exactly the same effect, or is there something I should be aware of?

Upvotes: 17

Views: 5312

Answers (3)

Keeg
Keeg

Reputation: 481

According to this site: http://en.csharp-online.net/CSharp_FAQ:_What_is_the_difference_between_CSharp_lock_and_Java_synchronized, C# lock and Java synchronized code blocks are "semantically identical", while for methods, Java uses synchronized while C# uses an attribute: [MethodImpl(MethodImplOptions.Synchronized)].

Upvotes: 12

Jon Skeet
Jon Skeet

Reputation: 1502016

One interesting difference not covered in the link posted by Keeg: as far as I'm aware, there's no equivalent method calls in Java for .NET's Monitor.Enter and Monitor.Exit, which the C# lock statement boils down to. That means you can't do the equivalent of Monitor.TryEnter either - although of course the java.util.concurrent.locks package (as of 1.5) has a variety of locks which have more features available.

Upvotes: 6

bh213
bh213

Reputation: 6539

I java you don't have to worry about locking public types that you own.

In .NET, you have to

Updated: this is for types that you own. Locking on public types that you don't own is bad in any language :)

Upvotes: -1

Related Questions