I am working on a program that creates about 50 threads that open new sockets. Occasionaly the user might want to cancel this action, which means all those threads have to be stopped (no, I don't use stop(), but I do set a flag, interrupt and join()). The thing is, it seems like new Socket(ip, port); is occasionaly getting stuck for large lengths of time if the ip or port isn't valid. I would like to know how to unblock this call (ie: cancel it). I've tried interrupt(), closing the (not yet created) socket and yelling at it. Nothing appears to work.
Joined: Sep 08, 2001
There appears to be no solution in Java 1.1, which I happen to know is what you were using at the time. The solution in later Javas (I think Java 1.4 and up) is to build a Socket object like this ->
This is, incidentally, a good example of why constructors with side effects are not a good idea. The point of a constructor is to allocate resources and return a usable object. Doing IO in a constructor is completely infuriating because
1) If you have IO you have threading since doing any IO on the event thread is asking for trouble
2) Usually you want to decide what to run on a thread first then have that code run on some specific thread. Doing IOin a constructor means that you need to pass all the params for the object and build it in the thread instead of passing the object itself - this can make code hard to make generic since the parameters needed to setup one type of object may be different for another.
3) It's surprising - people doing expect constructors to block!
4) It makes inheritance hierarchies difficult.
5) Most importantly, it basically ensures that there's no way to cancel the IO from another thread since there's no way to gain a reference to the object doing the IO. Not quickly freeing resources like io file descriptors and threads quickly means you will run out of resources if you're starting and stopping tasks quickly - like if a user it clicking on a search button madly..
This is in addition to all the other pre-existing constructor gotchas like letting object references escape in constructors and the confusing fun when constructors find themselves in inheritance hierarchies...
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: thread won't unblock from new Socket(ip, port);