Friday, September 12, 2014

Synchronized

  1. Synchronized is the keyword which can be apply for methods and blocks i.e. we can’t apply synchronized keyword for classes and variables.
  2. If a method declared as synchronized at a time only one thread is allowed to execute that method on the given object.
  3. Synchronized is the keyword which is always talks about implementation but abstract never talks about implementation. Hence synchronized and abstract combination is illegal for the methods.
Advantages: we can provide thread safety, we can avoid data inconsistency problems.
Disadvantages: Synchronized keyword increased weighting time of threads and hence performance of system goes down. Hence unless and until there is no specific requirement is not then don’t use synchronized keyword in the coding.

Native: The native is the keyword which can apply only for methods i.e. we can’t apply native keyword for classes and variables. A native method means the method which is implemented in non java like c or c++.  Native methods are also known as foreign methods.

Advantages:
1. As the performance of Java is low for improving the performance we can depend on c or c++. This usage can be happened by native keyword.
2. We can communicate Legacy systems by using native keyword.
class Native {
            static{
                        System.loadLibrary("path.of.native.library"); //1. Load native libraries
            }
            native void m1(); //2. Declaring a native method
}

class Client{
            public static void main (String args[]){
                        Native n = new Native();
                        n.m1(); //3. Invoke a native method
            }
}
3. For the native methods, already implementation is available, we are not providing any implementation. Hence native method declaration should be ends with “;”.
4. Native method means already implementation is available, but abstract method means implementation is not available. Hence abstract and native combination is illegal for the  methods.
5. Native & strictfp combination is illegal for methods, because the old languages may not follow IEEE 754 standard for the floating point arithmetic.
6. We can override a native method
Eg: It is recommended to override hascode() method (which is a native method in object class in our class)
    class Object{
                        native hasCode();
}

class Test{
                //override
}
7. We can overload a native method

native and final combination is legal


No comments:

Post a Comment