1 package org.sapia.ubik.net.mplex; 2 3 import java.io.IOException ; 4 5 import java.net.Socket ; 6 import java.net.SocketException ; 7 8 import java.util.Iterator ; 9 import java.util.LinkedList ; 10 11 12 41 public class SocketQueue { 42 43 private LinkedList _theSockets; 44 45 46 private boolean _isClosed; 47 48 49 private IOException _theLastException; 50 51 54 public SocketQueue() { 55 _theSockets = new LinkedList (); 56 _isClosed = false; 57 } 58 59 64 public synchronized void add(Socket aSocket) throws SocketException { 65 if (_isClosed) { 66 throw new SocketException ( 67 "Could not add socket - the socket queue is closed"); 68 } 69 70 _theLastException = null; 71 _theSockets.addLast(aSocket); 72 notify(); 73 } 74 75 81 public synchronized Socket getSocket() throws IOException { 82 if (_isClosed) { 83 throw new SocketException ( 84 "No socket available - the socket queue is closed"); 85 } else if (_theSockets.isEmpty()) { 86 try { 87 wait(); 88 } catch (InterruptedException ie) { 89 } 91 } 92 93 if (_isClosed) { 94 throw new SocketException ( 95 "No socket available - the socket queue is closed"); 96 } else if (_theLastException != null) { 97 IOException ioe = _theLastException; 98 _theLastException = null; 99 throw ioe; 100 } else if (_theSockets.isEmpty()) { 101 return getSocket(); 102 } else { 103 return (Socket ) _theSockets.removeFirst(); 104 } 105 } 106 107 110 public synchronized void close() { 111 _isClosed = true; 112 113 for (Iterator it = _theSockets.iterator(); it.hasNext();) { 114 Socket socket = (Socket ) it.next(); 115 116 try { 117 socket.close(); 118 } catch (IOException ioe) { 119 } 121 } 122 123 _theSockets.clear(); 124 notifyAll(); 125 } 126 127 132 public synchronized void setException(IOException anException) { 133 _theLastException = anException; 134 notify(); 135 } 136 137 142 public IOException getException() { 143 return _theLastException; 144 } 145 146 151 public int size() { 152 return _theSockets.size(); 153 } 154 } 155 | Popular Tags |