Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

locking effects in Java

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..

like image 490
OckhamsRazor Avatar asked Jan 02 '11 07:01

OckhamsRazor


People also ask

What is locking in Java?

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.

How many types of locking are there in Java?

there is two type of lock in java....

What is lock class 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.

What are locks in programming?

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.


1 Answers

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.

like image 191
Arjan Tijms Avatar answered Sep 22 '22 02:09

Arjan Tijms