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)
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
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
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
;
77 // Package-private to avoid a trampoline.
78 static Thread scavenger
;
80 // If client and server are in the same VM, serverobj represents server
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();
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(){
114 if (debug
) System
.out
.println("************* start scavenger.");
115 boolean liveon
= true;
117 // Sleep for the expire timeout
119 Thread
.sleep(UnicastConnection
.CONNECTION_TIMEOUT
);
120 }catch(InterruptedException _ie
){
124 // Scavenge all clients' connections that're expired
125 Iterator iter
= clients
.values().iterator();
126 long l
= System
.currentTimeMillis();
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;
136 UnicastConnection conn
= (UnicastConnection
)conns
.get(last
);
137 if (UnicastConnection
.isExpired(conn
, l
)){
142 liveon
= true; //there're still live connections
146 }catch(ConcurrentModificationException cme
) {
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);
162 * Client UnicastConnectionManager constructor
164 private UnicastConnectionManager(String host
, int port
, RMIClientSocketFactory csf
) {
168 serverFactory
= null;
170 connections
= new ArrayList();
174 * Server UnicastConnectionManager constructor
176 private UnicastConnectionManager(int port
, RMIServerSocketFactory ssf
) throws RemoteException
{
179 ssock
= ssf
.createServerSocket(port
);
180 serverPort
= ssock
.getLocalPort();
182 catch (IOException ioex
) {
185 throw new java
.rmi
.server
.ExportException("can not create Server Socket on port " + port
,ioex
);
187 serverName
= localhost
;
189 clientFactory
= null;
193 * Return a client connection manager which will connect to the given
196 public static synchronized UnicastConnectionManager
getInstance(String host
, int port
, RMIClientSocketFactory csf
) {
197 //System.out.println("getInstance: " + host + "," + port + "," + csf);
199 csf
= defaultSocketFactory
;
201 // change host name to host address to avoid name resolving issues
203 host
= InetAddress
.getByName(host
).getHostAddress();
204 }catch(Exception _
){}
206 TripleKey key
= new TripleKey(host
, port
, csf
);
207 UnicastConnectionManager man
= (UnicastConnectionManager
)clients
.get(key
);
209 man
= new UnicastConnectionManager(host
, port
, csf
);
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
;
226 * Return a server connection manager which will accept connection on the
229 public static synchronized UnicastConnectionManager
getInstance(int port
, RMIServerSocketFactory ssf
) throws RemoteException
{
230 //System.out.println("getInstance: " + port + "," + ssf);
232 ssf
= defaultSocketFactory
;
234 TripleKey key
= new TripleKey(localhost
, port
, ssf
);
235 UnicastConnectionManager man
= (UnicastConnectionManager
)servers
.get(key
);
237 man
= new UnicastConnectionManager(port
, ssf
);
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
);
250 * Get a connection from this manager.
252 public UnicastConnection
getConnection() throws IOException
{
254 return (getClientConnection());
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();
271 System
.out
.println("\n\n ****** " + nssock
+ " server socks.\n\n");
273 //System.out.println("Server connection " + sock);
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
289 conn
= (UnicastConnection
)conns
.get(nconn
);
290 //Should we check if conn is alive using Ping??
293 // Check if the connection is already expired
294 long l
= System
.currentTimeMillis();
295 if (!UnicastConnection
.isExpired(conn
, l
)){
304 Socket sock
= clientFactory
.createSocket(serverName
, serverPort
);
305 conn
= new UnicastConnection(this, sock
);
306 conn
.makeConnection(DEFAULT_PROTOCOL
);
310 System
.out
.println("\n\n ====== " + ncsock
+ " client socks.\n\n");
317 * Discard a connection when we're done with it - maybe it can be
320 public void discardConnection(UnicastConnection conn
) {
321 //System.out.println("Discarding connection " + conn);
323 if (ssock
!= null) //server connection
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)
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() {
343 if (ssock
== null || serverThread
!= null) {
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() {
358 if(serverThread
!= null){
362 }catch(Exception _
){}
368 * Server thread for connection manager.
371 for (;serverThread
!= null;) { // if serverThread==null, then exit thread
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
) {
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.
423 TripleKey(String host
, int port
, Object 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*/)) {