Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 549
Epaga Avatar asked Oct 20 '08 07:10

Epaga


People also ask

What is difference between synchronized and non synchronized?

Non synchronized -It is not-thread safe and can't be shared between many threads without proper synchronization code. While, Synchronized- It is thread-safe and can be shared with many threads.

What is the difference between synchronized and unsynchronized in Java?

Synchronized access means it is thread-safe. So different threads can access the collection concurrently without any problems, but it is probably a little bit slower depending on what you are doing. Unsynchronized is the opposite. Not thread-safe, but a little bit faster.

What is difference between concurrency and synchronization?

The word synchronization generally means sharing data between multiple processors or threads, while concurrency refers to a measure of– or the art of improving– how effectively an application allows multiple jobs required by that application (e.g. serving web page requests from a web server) to run simultaneously.

How locks are better than synchronized?

Lock framework works like synchronized blocks except locks can be more sophisticated than Java's synchronized blocks. Locks allow more flexible structuring of synchronized code.


2 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)].

like image 101
Keeg Avatar answered Sep 21 '22 18:09

Keeg


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.

like image 35
Jon Skeet Avatar answered Sep 19 '22 18:09

Jon Skeet