java - difference between the keywords volatile and syncronized -
this question has reply here:
difference between volatile , synchronized in java 4 answersin situation can volatile replace synchronized?also how can write operations on double , long become atomic after declaring them volatile
difference between volatile , synchronized in java
synchronized modifies code blocks , methods volatile keyword used modifier variable.
in java, volatile keyword synchronizes value of 1 variable between thread memory , main memory while synchronized keyword synchronizes value of variable between thread memory , main memory
volatile works faster compare synchronized because synchronized affects lot on performance due obtain , release of lock.
obtaining , releasing lock not required volatile necessary synchronized.
read article difference-between-volatile-and- synchronize.
explaining same here clarity -
int i1; int geti1() {return i1;} volatile int i2; int geti2() {return i2;} int i3; synchronized int geti3() {return i3;} geti1() accesses value stored in i1 in current thread. threads can have local copies of variables, , info not have same info held in other threads. in particular, thread may have updated i1 in it's thread, value in current thread different updated value. in fact java has thought of "main" memory, , memory holds current "correct" value variables. threads can have own re-create of info variables, , thread re-create can different "main" memory. in fact, possible "main" memory have value of 1 i1, thread1 have value of 2 i1 , thread2 have value of 3 i1 if thread1 , thread2 have both updated i1 updated value has not yet been propagated "main" memory or other threads.
on other hand, geti2() accesses value of i2 "main" memory. volatile variable not allowed have local re-create of variable different value held in "main" memory. effectively, variable declared volatile must have it's info synchronized across threads, whenever access or update variable in thread, other threads see same value. volatile variables have higher access , update overhead "plain" variables. threads allowed have own re-create of info improve efficiency.
executing geti3() following:
the thread acquires lock on monitor object . the thread memory flushes variables, i.e. has of variables read "main" memory . the code block executed (in case setting homecoming value current value of i3, may have been reset "main" memory). (any changes variables written out "main" memory, geti3() have no changes.) the thread releases lock on monitor object this.so volatile synchronizes value of 1 variable between thread memory , "main" memory, synchronized synchronizes value of variables between thread memory , "main" memory, , locks , releases monitor boot. synchronized have more overhead volatile.
java
No comments:
Post a Comment