Do these two keywords have exactly the same effect, or is there something I should be aware of?
3 Answers
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)]
.
-
Nope, "semantically identical" is what I needed to hear... and whether there were any "gotchas", but that page seems to be pretty clear. Thanks. Stackoverflow is my new Google. ;) – Epaga Oct 20 '08 at 07:32
-
2Page doesn't exist anymore. – Pierre Nov 30 '18 at 13:38
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.
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 :)

- 6,343
- 9
- 43
- 52
-
2No, it's still a bad idea to lock on public references in Java too. What makes you think it's okay in Java? – Jon Skeet Oct 20 '08 at 08:29
-
While an interesting link, it absoltely (and statedly) does not discuss the issue of locking public types. Which do I agree you shouldn't do... it is a shame that is how [MethodImpl] does it... – Marc Gravell Oct 20 '08 at 08:31
-
1lock on something public and wait for an idiot to put a deadlocking lock on it too. – Andrei Rînea Mar 05 '09 at 23:21
-
The only reason I can think of that locking on public types in Java may be safe, is perhaps it doesn't have the same "aggressive teardowns" of the app domain that a .net hosting environment (such as in SQL server) may do. In that case, the risk of orphaned locks wouldn't be as great (or even possible) in Java? I'm speculating. – Triynko Mar 31 '15 at 05:02