Question about practices of Java reference and synchronized keyword? -


i'm confused issue reference , synchronized keyword long time. see code this:

class someclass {     ...     private someobject mobject;     ...     public void somemethod() {         ...        final someobject obj = mobject;        ...        //then use 'obj' variable rather mobject        ...     } 

}

my question why should use local final variable obj replace member variable? why not use member variable directly?

i see example code associated 'synchronized' keyword,like this:

public void write(byte[] out) {     // create temporary object     connectedthread r;     // synchronize copy of connectedthread     synchronized (this) {         if (mstate != state_connected) return;         r = mconnectedthread;     }     // perform write unsynchronized     r.write(out); } 

why these code can achieve synchronized goal? thanks!

from can understand of question , first example, code trying avoid threading problems wanting take local copy of member variable. first example doesn't this, gets new local variable pointing same object member variable points to, doesn't protect invokations on object threading issues.

edit following @nick's comment: nick says, first example's somemethod method avoids possibility of having mobject being replaced instance half way through. doesn't protect against threading issues concurrent invokations on same instance.


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -