java - Need an interruptable way to listen for UDP packets in a worker thread -


i'm developing google glass app needs listen udp packets in worker thread (integrating existing system sends udp packets). posted question (see here) , received answer provided guidance on how this. using approach in other discussion i'll have worker thread blocked on datagramsocket.receive().

further reading suggests me i'll need able start/stop on demand. brings me question i'm posting here. how can above in such way able interrupt (gracefully) udp listening? there way can "nicely" ask socket break out of receive() call thread?

or there way listen udp packets in interruptable fashion can start/stop listener thread needed in response device events?

my recommendation:

private datagramsocket msocket;  @override public void run() {     exception ex = null;     try {         // read while not interrupted         while (!interrupted()) {             ....             msocket.receive(...); // excepts when interrupted         }     } catch (exception e) {         if (interrupted())             // user did         else             ex = e;     } {         // release         release();          // rethrow exception if need         if (ex != null)             throw ex;     } }  public void release() {     // causes exception if in middle of rcv      if (msocket != null) {         msocket.close();         msocket = null;     } }  @override public void interrupt() {     super.interrupt();     release(); } 

clean cut, simple, releases , interrupting stops cleanly in 2 cases.


Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -