Java: Get Notified On Incoming Packet
I'm working on a library that is currently using standard tcp sockets. An end user of my library registers themselves as a listener, and needs to be notified if/when a relevant message comes in.
If I spawn a worker thread within my library, there is a thread-death problem where my library may preve开发者_开发百科nt the application from terminating normally when all user-threads die.
Is there a way I can be notified of a new incoming tcp packet without spawning a new thread or requiring the user to poll the library?
Thanks!
Register the worker thread as a "daemon" to tell the JVM that it doesn't have to wait for your thread to exit.
http://download.oracle.com/javase/6/docs/api/java/lang/Thread.html#setDaemon(boolean)
I don't know about the sockets part, but if when you spawn the thread you mark it as a daemon thread (setDaemon(true)), then it won't stop the app exiting.
You can use the thread that's reading data from the socket. If the work is CPU-bound, you'll gain little by firing another thread just to dispatch the event.
On the other hand, if you're building a library you'll have no control on what the user will do when you call the listener's method, so I'd advise you to use an internal Executor and give your library a method like terminate(). Calling the listener's method would be delegated to a runnable, which you'd submit to the Executor (could be a newSingleThreadExecutor, newCachedThreadPool or whatever you think fits better).
This way, the users know they must call init() and terminate() - where init() would initialize the Executor and terminate() would take care of shutting it down. This allows you to have your own threads within your library and keep them from stopping the main application from shutting down
Take a look at this, might give you a better idea of what I'm talking about.
精彩评论