Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performance of synchronized method vs block

I've a class where all methods need to be synchronized (no static method). One of those method will be called once every 50 ms.

I'm wondering where putting the synchronized keyword to have the shortest execution time ?

i.e. Is there any differences between the 2 options detailed bellow regarding execution time ?

Option 1 (synchronized methods)

public class MyNativeObject{

     private boolean released = false;

     public synchronized String read(){
         if(released) return null;
         return Read(); 
     }

     public synchronized void release(){
         if(released) return;
         released = true;
         Release();
     }
     private native String Read();
     private native void Release();
}

Option 2 (synchronized block)

public class MyNativeObject{

     private Boolean released = false;

     public String read(){
         synchronized(released){
             if(released) return null;
             return Read(); 
         }
     }

     public void release(){
         synchronized(released){
             if(released) return;
             released = true;
             Release();
         }
     }
     private native String Read();
     private native void Release();
}
like image 225
ben75 Avatar asked Dec 17 '25 19:12

ben75


1 Answers

You can't have a synchronized class.

As Joachim points out, Option 2 is wrong as you are locking on a) a field which changes and b) a global object.

The synchronized methods is not only the only one which works but the simplest of those which would so I would use that.

A typical lock takes around 50 nano-seconds, so if you call these methods every 50,000,000 nano-seconds, it is highly unlikely that it will make any difference.

public class MyNativeObject{

     private boolean released = false;

     public synchronized String read(){
         return released ? null : Read(); 
     }

     public synchronized void release(){
         if(released) return;
         released = true;
         Release();
     }

     // make the native methods static if you can.
     private static native String Read();
     private static native void Release();
}
like image 69
Peter Lawrey Avatar answered Dec 20 '25 11:12

Peter Lawrey



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!