Merge from the pain train
[official-gcc.git] / libjava / gnu / java / rmi / server / UnicastConnectionManager.java
blobef01c8264e58166b28c3a2643b94395fb12b491a
1 /* UnicastConnectionManager.java --
2 Copyright (c) 1996, 1997, 1998, 1999, 2002, 2004
3 Free Software Foundation, Inc.
5 This file is part of GNU Classpath.
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING. If not, write to the
19 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20 02111-1307 USA.
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library. Thus, the terms and
24 conditions of the GNU General Public License cover the whole
25 combination.
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module. An independent module is a module which is not derived from
34 or based on this library. If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so. If you do not wish to do so, delete this
37 exception statement from your version. */
40 package gnu.java.rmi.server;
42 import gnu.java.rmi.server.RMIIncomingThread;
43 import gnu.java.rmi.server.UnicastConnection;
45 import java.io.IOException;
46 import java.io.ObjectOutput;
47 import java.io.ObjectInput;
48 import java.net.InetAddress;
49 import java.net.Socket;
50 import java.net.ServerSocket;
51 import java.net.UnknownHostException;
52 import java.rmi.RemoteException;
53 import java.rmi.server.RMISocketFactory;
54 import java.rmi.server.RMIServerSocketFactory;
55 import java.rmi.server.RMIClientSocketFactory;
56 import java.util.ArrayList;
57 import java.util.ConcurrentModificationException;
58 import java.util.Hashtable;
59 import java.util.Iterator;
61 public class UnicastConnectionManager
62 implements Runnable, ProtocolConstants {
64 private static String localhost;
65 // use different maps for server/client type UnicastConnectionManager
66 private static Hashtable servers = new Hashtable();
67 // Package-private to avoid trampolines.
68 static Hashtable clients = new Hashtable();
69 ArrayList connections; //client connection pool
71 // make serverThread volatile for poll
72 private volatile Thread serverThread;
73 private ServerSocket ssock;
74 String serverName;
75 int serverPort;
77 // Package-private to avoid a trampoline.
78 static Thread scavenger;
80 // If client and server are in the same VM, serverobj represents server
81 Object serverobj;
83 private static RMISocketFactory defaultSocketFactory = RMISocketFactory.getSocketFactory();
84 private RMIServerSocketFactory serverFactory;
85 private RMIClientSocketFactory clientFactory;
87 // The following is for debug
88 private static int ncsock = 0; //count of client socket
89 private static int nssock = 0; //count of server socket
90 private static int ncmanager = 0; //count of client manager
91 private static int nsmanager = 0; //count of server manager
93 private static final boolean debug = false;
95 private static final Object GLOBAL_LOCK = new Object();
97 static {
98 try {
99 //Use host address instead of host name to avoid name resolving issues
100 //localhost = InetAddress.getLocalHost().getHostName();
101 localhost = InetAddress.getLocalHost().getHostAddress();
103 catch (UnknownHostException _) {
104 localhost = "localhost";
110 //Only one scavenger thread running globally
111 private static void startScavenger(){
112 scavenger = new Thread(new Runnable(){
113 public void run(){
114 if (debug) System.out.println("************* start scavenger.");
115 boolean liveon = true;
116 while (liveon){
117 // Sleep for the expire timeout
118 try{
119 Thread.sleep(UnicastConnection.CONNECTION_TIMEOUT);
120 }catch(InterruptedException _ie){
121 break;
123 liveon = false;
124 // Scavenge all clients' connections that're expired
125 Iterator iter = clients.values().iterator();
126 long l = System.currentTimeMillis();
127 try{
128 while(iter.hasNext()){
129 UnicastConnectionManager man = (UnicastConnectionManager)iter.next();
130 ArrayList conns = man.connections;
131 synchronized(conns) { // is the lock a little coarser?
132 for (int last = conns.size() - 1;
133 last >= 0;
134 --last)
136 UnicastConnection conn = (UnicastConnection)conns.get(last);
137 if (UnicastConnection.isExpired(conn, l)){
138 conns.remove(last);
139 conn.disconnect();
140 conn = null;
141 }else
142 liveon = true; //there're still live connections
146 }catch(ConcurrentModificationException cme) {
147 // handle it lazily
148 liveon = true;
151 scavenger = null;
152 if (debug) System.out.println("************* exit scavenger.");
155 // As it is used for client connection, we may put this thread
156 // in daemon state to prevent the VM from blocking when exiting.
157 scavenger.setDaemon(true);
158 scavenger.start();
162 * Client UnicastConnectionManager constructor
164 private UnicastConnectionManager(String host, int port, RMIClientSocketFactory csf) {
165 ssock = null;
166 serverName = host;
167 serverPort = port;
168 serverFactory = null;
169 clientFactory = csf;
170 connections = new ArrayList();
174 * Server UnicastConnectionManager constructor
176 private UnicastConnectionManager(int port, RMIServerSocketFactory ssf) throws RemoteException {
178 try {
179 ssock = ssf.createServerSocket(port);
180 serverPort = ssock.getLocalPort();
182 catch (IOException ioex) {
183 ssock = null;
184 serverPort = 0;
185 throw new java.rmi.server.ExportException("can not create Server Socket on port " + port,ioex);
187 serverName = localhost;
188 serverFactory = ssf;
189 clientFactory = null;
193 * Return a client connection manager which will connect to the given
194 * host/port.
196 public static synchronized UnicastConnectionManager getInstance(String host, int port, RMIClientSocketFactory csf) {
197 //System.out.println("getInstance: " + host + "," + port + "," + csf);
198 if (csf == null) {
199 csf = defaultSocketFactory;
201 // change host name to host address to avoid name resolving issues
202 try{
203 host = InetAddress.getByName(host).getHostAddress();
204 }catch(Exception _){}
206 TripleKey key = new TripleKey(host, port, csf);
207 UnicastConnectionManager man = (UnicastConnectionManager)clients.get(key);
208 if (man == null) {
209 man = new UnicastConnectionManager(host, port, csf);
210 if (debug) {
211 ncmanager++;
212 System.out.println("\n\n ====== " + ncmanager + " client managers.\n\n");
214 clients.put(key, man);
216 // Detect if client and server are in the same VM, i.e., their keys are equal
217 UnicastConnectionManager svrman = (UnicastConnectionManager)servers.get(key);
218 if(svrman != null){ // server and client are in the same VM
219 man.serverobj = svrman.serverobj;
222 return (man);
226 * Return a server connection manager which will accept connection on the
227 * given port.
229 public static synchronized UnicastConnectionManager getInstance(int port, RMIServerSocketFactory ssf) throws RemoteException {
230 //System.out.println("getInstance: " + port + "," + ssf);
231 if (ssf == null) {
232 ssf = defaultSocketFactory;
234 TripleKey key = new TripleKey(localhost, port, ssf);
235 UnicastConnectionManager man = (UnicastConnectionManager)servers.get(key);
236 if (man == null) {
237 man = new UnicastConnectionManager(port, ssf);
238 if (debug) {
239 nsmanager++;
240 System.out.println("\n\n ****** " + nsmanager + " server managers.\n\n");
242 // The provided port might not be the set port.
243 key.port = man.serverPort;
244 servers.put(key, man);
246 return (man);
250 * Get a connection from this manager.
252 public UnicastConnection getConnection() throws IOException {
253 if (ssock == null) {
254 return (getClientConnection());
256 else {
257 return (getServerConnection());
262 * Accept a connection to this server.
264 private UnicastConnection getServerConnection() throws IOException {
265 Socket sock = ssock.accept();
266 sock.setTcpNoDelay(true); //??
267 UnicastConnection conn = new UnicastConnection(this, sock);
268 conn.acceptConnection();
269 if (debug){
270 nssock++;
271 System.out.println("\n\n ****** " + nssock + " server socks.\n\n");
273 //System.out.println("Server connection " + sock);
274 return (conn);
278 * Make a conection from this client to the server.
280 private UnicastConnection getClientConnection() throws IOException {
281 ArrayList conns = connections;
282 UnicastConnection conn;
284 synchronized(conns) {
285 int nconn = conns.size() - 1;
287 // if there're free connections in connection pool
288 if(nconn >= 0) {
289 conn = (UnicastConnection)conns.get(nconn);
290 //Should we check if conn is alive using Ping??
291 conns.remove(nconn);
293 // Check if the connection is already expired
294 long l = System.currentTimeMillis();
295 if (!UnicastConnection.isExpired(conn, l)){
296 return conn;
297 }else {
298 conn.disconnect();
299 conn = null;
304 Socket sock = clientFactory.createSocket(serverName, serverPort);
305 conn = new UnicastConnection(this, sock);
306 conn.makeConnection(DEFAULT_PROTOCOL);
308 if (debug) {
309 ncsock++;
310 System.out.println("\n\n ====== " + ncsock + " client socks.\n\n");
313 return (conn);
317 * Discard a connection when we're done with it - maybe it can be
318 * recycled.
320 public void discardConnection(UnicastConnection conn) {
321 //System.out.println("Discarding connection " + conn);
322 //conn.disconnect();
323 if (ssock != null) //server connection
324 conn.disconnect();
325 else {
326 // To client connection, we'd like to return back to pool
327 UnicastConnection.resetTime(conn);
328 //Ensure there're only one scavenger globally
329 synchronized(GLOBAL_LOCK) {
330 connections.add(conn); //borrow this lock to garantee thread safety
331 if (scavenger == null)
332 startScavenger();
338 * Start a server on this manager if it's a server socket and we've not
339 * already got one running.
341 public void startServer() {
342 synchronized(this) {
343 if (ssock == null || serverThread != null) {
344 return;
346 serverThread = new Thread(this);
347 // The following is not necessary when java.lang.Thread's constructor do this.
348 // serverThread.setContextClassLoader(Thread.currentThread().getContextClassLoader());
350 serverThread.start();
354 * Stop a server on this manager
356 public void stopServer() {
357 synchronized(this) {
358 if(serverThread != null){
359 serverThread = null;
360 try{
361 ssock.close();
362 }catch(Exception _){}
368 * Server thread for connection manager.
370 public void run() {
371 for (;serverThread != null;) { // if serverThread==null, then exit thread
372 try {
373 //System.out.println("Waiting for connection on " + serverPort);
374 UnicastConnection conn = getServerConnection();
376 // get address of remote host for the RMIIncomingThread object
377 String remoteHost = null;
378 if (conn.sock != null) {
379 remoteHost = conn.sock.getInetAddress().getHostAddress();
382 // use a thread pool to improve performance
383 //ConnectionRunnerPool.dispatchConnection(conn);
384 (new RMIIncomingThread(conn, remoteHost)).start();
385 // (new Thread(conn)).start();
387 catch (Exception e) {
388 e.printStackTrace();
394 * Serialization routine.
396 void write(ObjectOutput out) throws IOException {
397 out.writeUTF(serverName);
398 out.writeInt(serverPort);
402 * Serialization routine.
404 static UnicastConnectionManager read(ObjectInput in) throws IOException {
405 String host = in.readUTF();
406 int port = in.readInt();
407 //RMIClientSocketFactory csf = ((RMIObjectInputStream)in).manager.clientFactory;
408 //return (getInstance(host, port, csf));
409 return (getInstance(host, port, null));
415 * This is use as the hashkey for the client/server connections.
417 class TripleKey {
419 String host;
420 int port;
421 Object other;
423 TripleKey(String host, int port, Object other) {
424 this.host = host;
425 this.port = port;
426 this.other = other;
430 * Hash code just include the host and other - we ignore the port since
431 * this has unusual matching behaviour.
433 public int hashCode() {
434 return (host.hashCode() ^ other.hashCode());
437 public boolean equals(Object obj) {
438 if (obj instanceof TripleKey) {
439 TripleKey other = (TripleKey)obj;
440 if (this.host.equals(other.host) &&
441 this.other == other.other &&
442 (this.port == other.port /* || this.port == 0 || other.port == 0*/)) {
443 return (true);
446 return (false);