Static Variable: If two Threads(suppose Thread 1 and Thread 2) are accessing the same object and updating a variable which is declared as static then it means Thread 1 and Thread 2 can make their own local copy of the same object(including static variables) in their respective cache, so updating by Thread 1 to the static variable in its local cache wont reflect in the static variable for Thread 2 cache . Static variables are used in the Object Context where updating by one object would reflect in all the other objects of the same class but not in the Thread context where updating of one thread to the static variable will reflect the changes immediately to all the threads (in their local cache).
Volatile variable: If two Threads(suppose Thread 1 and Thread 2) are accessing the same object and updating a variable which is declared as volatile then it means Thread 1 and Thread 2 can make their own local cache of the Object except the variable which is declared as a volatile . So the volatile variable will have only one main copy which will be updated by different threads and updating by one thread to the volatile variable will immediately reflect to the other Thread. So the volatile variable is used in the Thread context.
for further understanding refer the following image.
awesome
ReplyDeletethanks!
ReplyDelete