java synchronized keyword needed on primitive getter / setter method? -


i read java code, , found these functions:

synchronized void setconnected(boolean connected){    this.connected = connected; }  synchronized boolean isconnected(){    return connected; } 

i wonder if synchronization makes sense here, or author didn't understand need synchronized keyword?

i'd suppose synchronized useless here. or mistaken?

the keyword synchronized 1 way of ensuring thread-safety. beware: there's (way) more thread-safety deadlocks, or missing updates because of 2 threads incrementing int without synchronization.

consider following class:

class connection {   private boolean connected;    synchronized void setconnected(boolean connected){     this.connected = connected;   }   synchronized boolean isconnected(){     return connected;   } } 

if multiple threads share instance of connection , 1 thread calls setconnected(true), without synchronized possible other threads keep seeing isconnected() == false. synchronized keyword guarantees threads sees current value of field.

in more technical terms, synchronized keyword ensures memory barrier (hint: google that).

in more details: every write made before releasing monitor (ie, before leaving synchronized block) guaranteed seen every read made after acquiring same monitor (ie, after entering block synchronizing on same object). in java, there's called happens-before (hint: google that), not trivial "i wrote code in order, things executed in order". using synchronized way establish happens-before relationship , guarantee threads see memory expect them see.

another way achieve same guarantees, in case, eliminate synchronized keyword , mark field volatile. guarantees provided volatile follows: writes made thread before volatile write guaranteed visible thread after subsequent volatile read of same field.

as final note, in particular case might better use volatile field instead of synchronized accessors, because 2 approaches provide same guarantees , volatile-field approach allows simultaneous accesses field different threads (which might improve performance if synchronized version has contention).


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -