does anybody know the effects of locking in Java specifically on the speed of execution of the program? if any, how do we overcome this effect? concrete references are appreciated..
Java lock acts as thread synchronization mechanisms that are similar to the synchronized blocks. After some time, a new locking mechanism was introduced. It is very flexible and provides more options in comparison to the Synchronized block.
there is two type of lock in java....
Class level lock prevents multiple threads to enter a synchronized block in any of all available instances of the class on runtime. This means if in runtime there are 10 instances of a class, only one thread will be able to access only one method or block of any one instance at a time.
A lock is a mechanism for controlling access to something. In programming, locks are often used so that multiple programs or threads of a program can share a resource - for example, access to a file for updating it - on a one-at-a-time basis.
If your application is mainly single threaded you may see no or very little performance degradation when doing too much locking.
In general a single lock can be grabbed very fast and efficiently when using the java.concurrent libraries or the build-in synchronized keyword. They use techniques like Lock elision, adaptive locking and lock coarsening (see Synchronization optimizations in Mustang), which basically means the compiler and/or library do some very smart things to optimize lock usage.
This especially plays out in situations where the lock wouldn't really be needed; the compiler optimizes it away.
However, when a lot of threads need to grab the same locks you'll eventually notice that the CPU load of your cores will never reach 100% for a pure computational problem. In effect, something is not going as fast as it possibly could, and your CPU is just sitting idle.
In absence of (heavy) IO this is often a sign of excessive lock contention
and this thus indeed degrades overall system performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With