Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Synchronization at multiple level

As shown in example below, once lock is taken on an object in call method, there is no need for further methods to have synchronized keyword.

public class Prac
{ 
    public static void main(String[] args)
    {
      new Prac().call();
    }

    private synchronized void call()
    {
      further();
    }

    private synchronized void further()
    {
      oneMore();
    }

    private synchronized void oneMore()
    {
      // do something
    }
}

But, if I still add synchronized keyword to further and onceMore, how will performance be impacted? Or not impacted at all?

EDIT : Does it add costs of checking(after encountering synchronized keyword) if it has lock or lock is required? Internally does this checking adds overhead?

EDIT : application will not have one thread only, this code here is just sample code. may be replace main with run method

like image 773
codingenious Avatar asked Sep 02 '26 02:09

codingenious


2 Answers

The performance will not be impacted. Acquiring a lock, which is already acquired costs nothing. This technique is called biased locking. By default biased locking is switched on. That's why single thread applications are not impacted by calling synchronized methods.

Java SE 6 Performance White Paper:

An object is "biased" toward the thread which first acquires its monitor via a monitorenter bytecode or synchronized method invocation; subsequent monitor-related operations can be performed by that thread without using atomic operations resulting in much better performance, particularly on multiprocessor machines.

like image 130
Mikhail Avatar answered Sep 04 '26 15:09

Mikhail


synchronization mechanism make methods a little bit slower so try to not synchronize method if you have only one thread

like image 44
nil Avatar answered Sep 04 '26 15:09

nil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!