How do I implement a timeout using Java threads? Specifically, I want to connect to one of two servers. If the first one fails after a certain amount of time, I want to try the second one. How do I interrupt the first connection attempt?

Francois Nadeau

Here's how I would do it. I would have 2 Threads. The first one would try to compunicate to the server. The second one would keep track of the time spent communicating. inside the run methode of the one calling onto an other server place a try catch code to catch an InterruptedException exception. In the catch make the needed changes, ie. give a need server address and restart.

public void run() {
  while( !connected ) 
    try {
      connectToServer() ;
    }catch( InterruptedException ie ) {
      //set a different server name