public synchronized void connect(long timeout) throws TransportException { try { switch (state) { case 0: break; case 3: return; // already connected case 4: state = 0; throw new TransportException("Connection in error", te); default: TransportException te = new TransportException("Invalid state: " + state); state = 0; throw te; } state = 1; te = null; thread = new Thread(this, name); thread.setDaemon(true); synchronized (thread) { thread.start(); thread.wait(timeout); /* wait for doConnect */ switch (state) { case 1: /* doConnect never returned */ state = 0; thread = null; throw new TransportException("Connection timeout"); case 2: if (te != null) { /* doConnect throw Exception */ state = 4; /* error */ thread = null; throw te; } state = 3; /* Success! */ return; } } } catch (InterruptedException ie) { state = 0; thread = null; throw new TransportException(ie); } finally { /* This guarantees that we leave in a valid state */ if (state != 0 && state != 3 && state != 4) { if (log.level >= 1) log.println("Invalid state: " + state); state = 0; thread = null; } } }