Java:: volatile, synchronized, static, transient, native, final, strictfp
volatile
1. The volatile keyword in Java is only application to a variable and using volatile keyword with class and method is illegal.
2. volatile keyword in Java guarantees that value of the volatile variable will always be read from main memory and not from Thread's local cache.
3. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and double variables).
4. Using the volatile keyword in Java on variables reduces the risk of memory consistency errors because any write to a volatile variable in Java establishes a happens-before relationship with subsequent reads of that same variable.
5. From Java 5 changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable in Java, it sees not just the latest change to the volatile variable but also the side effects of the code that led up the change.
6. Reads and writes are atomic for reference variables are for most primitive variables (all types except long and double) even without the use of volatile keyword in Java.
7. An access to a volatile variable in Java never has a chance to block, since we are only doing a simple read or write, so unlike a synchronized block we will never hold on to any lock or wait for any lock.
8. Java volatile variable that is an object reference may be null.
9. Java volatile keyword doesn't mean atomic, its common misconception that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java.
10. If a variable is not shared between multiple threads, you don't need to use volatile keyword with that variable.
synchronized
1. synchronized instance method: Instance methods are synchronized over the instance of the class owning the method. Which means only one thread per instance of the class can execute this method.
2. synchronized static method: These methods are synchronized on the Class object associated with the class and since only one Class object exists per JVM per class, only one thread can execute inside a static synchronized method per class, irrespective of the number of instances it has.
3. synchronized block within method: we passed a parameter this for object lock or ClassName.class for class lock, to the synchronized block. This is the monitor object/class, the code inside the block get synchronized on the monitor object/class. Simply put, only one thread per monitor object/(one object per class) can execute inside that block of code.
Static click here
transient
1. Can be used with varibale
2. When serialization of object happens, the value of transient variable will not be saved in the file.
3. Can be used when I don't want to save private data, or value of the property can be determined from serialized object
4. transient and static : Since static fields are not part of state of the object, there is no use/impact of using transient keyword with static variables. However there is no compilation error.
5. transient and final : final variables are directly serialized by their values, so there is no use/impact of declaring final variable as transient. There is no compile-time error though.
// Java program to demonstrate transient keyword
// Filename Test.java
import java.io.*;
class Test implements Serializable
{
// Normal variables
int i = 10, j = 20;
// Transient variables
transient int k = 30;
// Use of transient has no impact here
transient static int l = 40;
transient final int m = 50;
public static void main(String[] args) throws Exception
{
Test input = new Test();
// serialization
FileOutputStream fos = new FileOutputStream("abc.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(input);
// de-serialization
FileInputStream fis = new FileInputStream("abc.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Test output = (Test)ois.readObject();
System.out.println("i = " + output.i);
System.out.println("j = " + output.j);
System.out.println("k = " + output.k);
System.out.println("l = " + output.l);
System.out.println("m = " + output.m);
}
}
native
1. The native keyword is applied to a method to indicates that the method is implemented in native code using JNI (Java Native Interface). native is a modifier applicable only for methods and we can’t apply it anywhere else. The methods which are implemented in C, C++ are called as native methods or foreign methods.
final
1. value of final variable cannot be changed
2. initialize the value of final variable before use, else compile error
3. if final variable is reference, it cannot re-bound to refer to another object
4. Use final variable when it's value needed to be same in whole execution of program
5. Use final method when I don't want to allow to overriding. For example few methods (getClass(), notify(), notifyAll(), wait() etc) of Object class
6. Use final class when I want to prevent inheritance. For example Wrapper (Float, Double etc.) classes or immutable classes like String
strictfp
1. The volatile keyword in Java is only application to a variable and using volatile keyword with class and method is illegal.
2. volatile keyword in Java guarantees that value of the volatile variable will always be read from main memory and not from Thread's local cache.
3. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and double variables).
4. Using the volatile keyword in Java on variables reduces the risk of memory consistency errors because any write to a volatile variable in Java establishes a happens-before relationship with subsequent reads of that same variable.
5. From Java 5 changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable in Java, it sees not just the latest change to the volatile variable but also the side effects of the code that led up the change.
6. Reads and writes are atomic for reference variables are for most primitive variables (all types except long and double) even without the use of volatile keyword in Java.
7. An access to a volatile variable in Java never has a chance to block, since we are only doing a simple read or write, so unlike a synchronized block we will never hold on to any lock or wait for any lock.
8. Java volatile variable that is an object reference may be null.
9. Java volatile keyword doesn't mean atomic, its common misconception that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java.
10. If a variable is not shared between multiple threads, you don't need to use volatile keyword with that variable.
synchronized
1. synchronized instance method: Instance methods are synchronized over the instance of the class owning the method. Which means only one thread per instance of the class can execute this method.
2. synchronized static method: These methods are synchronized on the Class object associated with the class and since only one Class object exists per JVM per class, only one thread can execute inside a static synchronized method per class, irrespective of the number of instances it has.
3. synchronized block within method: we passed a parameter this for object lock or ClassName.class for class lock, to the synchronized block. This is the monitor object/class, the code inside the block get synchronized on the monitor object/class. Simply put, only one thread per monitor object/(one object per class) can execute inside that block of code.
Static click here
transient
1. Can be used with varibale
2. When serialization of object happens, the value of transient variable will not be saved in the file.
3. Can be used when I don't want to save private data, or value of the property can be determined from serialized object
4. transient and static : Since static fields are not part of state of the object, there is no use/impact of using transient keyword with static variables. However there is no compilation error.
5. transient and final : final variables are directly serialized by their values, so there is no use/impact of declaring final variable as transient. There is no compile-time error though.
// Java program to demonstrate transient keyword
// Filename Test.java
import java.io.*;
class Test implements Serializable
{
// Normal variables
int i = 10, j = 20;
// Transient variables
transient int k = 30;
// Use of transient has no impact here
transient static int l = 40;
transient final int m = 50;
public static void main(String[] args) throws Exception
{
Test input = new Test();
// serialization
FileOutputStream fos = new FileOutputStream("abc.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(input);
// de-serialization
FileInputStream fis = new FileInputStream("abc.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Test output = (Test)ois.readObject();
System.out.println("i = " + output.i);
System.out.println("j = " + output.j);
System.out.println("k = " + output.k);
System.out.println("l = " + output.l);
System.out.println("m = " + output.m);
}
}
Output :
i = 10 j = 20 k = 0 l = 40 m = 50
native
1. The native keyword is applied to a method to indicates that the method is implemented in native code using JNI (Java Native Interface). native is a modifier applicable only for methods and we can’t apply it anywhere else. The methods which are implemented in C, C++ are called as native methods or foreign methods.
2. The main objective of native keyword are:
2.1. To improve performance of the system.
2.2. To achieve mission level/memory level communication.
2.3. To use already existing legacy non-java code.
3. Important points about native keyword:
3.1. For native methods implementation is already available in old languages like C, C++ and we are not responsible to provide implementation. Hence native method declaration should ends with ;( semi-colon).
3.2. We can’t declare native method as abstract.
3.3. We can’t declare native method as strictfp because there is no guarantee that old languages (C, C++) follow IEEE 754 standard. Hence native strictfp combination is illegal combination for methods.
3.4. The main advantage of native keyword is performance will be improved but the main disadvantage of native keyword is it breaks platform independent nature of java.
final
1. value of final variable cannot be changed
2. initialize the value of final variable before use, else compile error
3. if final variable is reference, it cannot re-bound to refer to another object
4. Use final variable when it's value needed to be same in whole execution of program
5. Use final method when I don't want to allow to overriding. For example few methods (getClass(), notify(), notifyAll(), wait() etc) of Object class
6. Use final class when I want to prevent inheritance. For example Wrapper (Float, Double etc.) classes or immutable classes like String
strictfp
strictfp is a keyword in java used for restricting floating-point calculations and ensuring same result on every platform while performing operations in the floating-point variable.
Floating point calculations are platform dependent i.e. different output(floating-point values) is achieved when a class file is run on different platforms(16/32/64 bit processors). To solve this types of issue, strictfp keyword was introduced in JDK 1.2 version by following IEEE 754 standards for floating-point calculations.
Floating point calculations are platform dependent i.e. different output(floating-point values) is achieved when a class file is run on different platforms(16/32/64 bit processors). To solve this types of issue, strictfp keyword was introduced in JDK 1.2 version by following IEEE 754 standards for floating-point calculations.
- Important points:
- strictfp modifier is used with classes, interfaces and methods only.
strictfp class Test { // all concrete methods here are // implicitly strictfp. } strictfp interface Test { // all methods here becomes implicitly // strictfp when used during inheritance. } class Car { // strictfp applied on a concrete method strictfp void calculateSpeed(){} }
- When a class or an interface is declared with strictfp modifier, then all methods declared in the class/interface, and all nested types declared in the class, are implicitly strictfp.
- strictfp cannot be used with abstract methods. However, it can be used with abstract classes/interfaces.
- Since methods of an interface are implicitly abstract, strictfp cannot be used with any method inside an interface.
strictfp interface Test { double sum(); strictfp double mul(); // compile-time error here }
//Java program to illustrate strictfp modifier
public
class
Test
{
// calculating sum using strictfp modifier
public
strictfp
double
sum()
{
double
num1 = 10e+
10
;
double
num2 = 6e+
08
;
return
(num1+num2);
}
public
static
strictfp
void
main(String[] args)
{
Test t =
new
Test();
System.out.println(t.sum());
}
}
Output:
1.006E11
Comments
Post a Comment