java - Is my code thread safe? -


in java application, have string (mysingleton.getinstance().mystring) gets updated based on user actions. in application, there tcp server sends value of string connected clients whenever value of string changes.

each client socket gets own thread. here thread code.

    public void run() {         try {             printstream printstream = new printstream(hostthreadsocket.getoutputstream(), true);             while (true) {                 synchronized (mysingleton.getinstance()) {                  printstream.println(mysingleton.getinstance().mystring);                     try {                         mysingleton.getinstance().wait();                     } catch (interruptedexception e) {                         e.printstacktrace();                     }                 }             }         } catch (ioexception e) {             e.printstacktrace();         }     } 

and here code writes mysingleton.getinstance().mystring.

    public void updatestring(string newstring) {         synchronized (mysingleton.getinstance()) {             mysingleton.getinstance().mystring = newstring;             mysingleton.getinstance().notifyall();         }     } 

i not familiar synchronization in java not confident code. can notice wrong?

it should fine, provided mysingleton.getinstance() returns same object.

if method call returns different objects @ different points in time, may exceptions due synchronizing on 1 instance, , calling wait or notify on different instance. in addition, there may memory hazards because not synchronizing on object accessing / updating.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -