java - Managing a Process inside a Thread -


i'm creating graphical interface runs threads. each 1 of these threads launch java process manage vnc connection. want keep track of process lifecycle storing in variables of thread manages. finally, gui communicates thread know process status.

here snippet of code:

public class vncviewer extends thread{     private static final string cmd = "some command";     private process vnc;     private boolean active = false ;      public void run(){         try {             launchvnc();         } catch (ioexception ex) {             logger.getlogger(vncviewer.class.getname()).log(level.severe, null, ex);         } catch (interruptedexception ex) {             logger.getlogger(vncviewer.class.getname()).log(level.severe, null, ex);         }     }      private void launchvnc() throws ioexception, interruptedexception{         if (condition){             vnc = runtime.getruntime().exec(cmd);             active = true;             while(vnc.isalive()){} //while process alive, thread awaits             active = false;         }     }      public boolean isactive(){         return active;     } } 

what happens @ runtime thread skips "while" loop (i've tried inserting system.out.println inside loop , printed when thread terminated), result variable "active" on "false".

since active not volatile, isn't updated/accessed in synchronized block , isn't 1 of atomic* classes, legal java vm assume no-one reads field between active=true , active=false.

therefore can decide ignore active=true (or more precise, not publish new value other threads).

you need synchronize code correctly, in case declaring field volatile adequate:

private volatile boolean active = false; 

this ensures updates field published , other thread reading field see updated one.

i'm still not convinced spinning external process shut down that's different matter.


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -