2 Copyright (c) 1996, 1997, 1998, 1999, 2002 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
38 package gnu
.java
.rmi
.server
;
40 import java
.rmi
.server
.RMISocketFactory
;
41 import java
.rmi
.server
.RMIServerSocketFactory
;
42 import java
.rmi
.server
.RMIClientSocketFactory
;
43 import java
.rmi
.RemoteException
;
44 import java
.io
.IOException
;
45 import java
.io
.ObjectOutput
;
46 import java
.io
.ObjectInput
;
47 import java
.io
.DataInputStream
;
48 import java
.lang
.Thread
;
49 import java
.lang
.Runnable
;
50 import java
.net
.InetAddress
;
51 import java
.net
.Socket
;
52 import java
.net
.ServerSocket
;
53 import java
.net
.UnknownHostException
;
55 import java
.util
.ArrayList
;
56 import java
.util
.ConcurrentModificationException
;
57 import java
.util
.Enumeration
;
58 import java
.util
.Hashtable
;
59 import java
.util
.Iterator
;
61 import gnu
.java
.rmi
.server
.UnicastConnection
;
63 public class UnicastConnectionManager
64 implements Runnable
, ProtocolConstants
{
66 private static String localhost
;
67 // use different maps for server/client type UnicastConnectionManager
68 private static Hashtable servers
= new Hashtable();
69 private static Hashtable clients
= new Hashtable();
70 private ArrayList connections
; //client connection pool
72 // make serverThread volatile for poll
73 private volatile Thread serverThread
;
74 private ServerSocket ssock
;
78 static private 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.");
159 * Client UnicastConnectionManager constructor
161 private UnicastConnectionManager(String host
, int port
, RMIClientSocketFactory csf
) {
165 serverFactory
= null;
167 connections
= new ArrayList();
171 * Server UnicastConnectionManager constructor
173 private UnicastConnectionManager(int port
, RMIServerSocketFactory ssf
) {
175 ssock
= ssf
.createServerSocket(port
);
176 serverPort
= ssock
.getLocalPort();
178 catch (IOException _
) {
180 ssock
= ssf
.createServerSocket(0);
181 serverPort
= ssock
.getLocalPort();
183 catch (IOException __
) {
188 serverName
= localhost
;
190 clientFactory
= null;
194 * Return a client connection manager which will connect to the given
197 public static synchronized UnicastConnectionManager
getInstance(String host
, int port
, RMIClientSocketFactory csf
) {
198 //System.out.println("getInstance: " + host + "," + port + "," + csf);
200 csf
= defaultSocketFactory
;
202 // change host name to host address to avoid name resolving issues
204 host
= InetAddress
.getByName(host
).getHostAddress();
205 }catch(Exception _
){}
207 TripleKey key
= new TripleKey(host
, port
, csf
);
208 UnicastConnectionManager man
= (UnicastConnectionManager
)clients
.get(key
);
210 man
= new UnicastConnectionManager(host
, port
, csf
);
213 System
.out
.println("\n\n ====== " + ncmanager
+ " client managers.\n\n");
215 clients
.put(key
, man
);
217 // Detect if client and server are in the same VM, i.e., their keys are equal
218 UnicastConnectionManager svrman
= (UnicastConnectionManager
)servers
.get(key
);
219 if(svrman
!= null){ // server and client are in the same VM
220 man
.serverobj
= svrman
.serverobj
;
227 * Return a server connection manager which will accept connection on the
230 public static synchronized UnicastConnectionManager
getInstance(int port
, RMIServerSocketFactory ssf
) {
231 //System.out.println("getInstance: " + port + "," + ssf);
233 ssf
= defaultSocketFactory
;
235 TripleKey key
= new TripleKey(localhost
, port
, ssf
);
236 UnicastConnectionManager man
= (UnicastConnectionManager
)servers
.get(key
);
238 man
= new UnicastConnectionManager(port
, ssf
);
241 System
.out
.println("\n\n ****** " + nsmanager
+ " server managers.\n\n");
243 // The provided port might not be the set port.
244 key
.port
= man
.serverPort
;
245 servers
.put(key
, man
);
251 * Get a connection from this manager.
253 public UnicastConnection
getConnection() throws IOException
{
255 return (getClientConnection());
258 return (getServerConnection());
263 * Accept a connection to this server.
265 private UnicastConnection
getServerConnection() throws IOException
{
266 Socket sock
= ssock
.accept();
267 sock
.setTcpNoDelay(true); //??
268 UnicastConnection conn
= new UnicastConnection(this, sock
);
269 conn
.acceptConnection();
272 System
.out
.println("\n\n ****** " + nssock
+ " server socks.\n\n");
274 //System.out.println("Server connection " + sock);
279 * Make a conection from this client to the server.
281 private UnicastConnection
getClientConnection() throws IOException
{
282 ArrayList conns
= connections
;
283 UnicastConnection conn
;
285 synchronized(conns
) {
286 int nconn
= conns
.size() - 1;
288 // if there're free connections in connection pool
290 conn
= (UnicastConnection
)conns
.get(nconn
);
291 //Should we check if conn is alive using Ping??
294 // Check if the connection is already expired
295 long l
= System
.currentTimeMillis();
296 if (!UnicastConnection
.isExpired(conn
, l
)){
305 Socket sock
= clientFactory
.createSocket(serverName
, serverPort
);
306 conn
= new UnicastConnection(this, sock
);
307 conn
.makeConnection(DEFAULT_PROTOCOL
);
311 System
.out
.println("\n\n ====== " + ncsock
+ " client socks.\n\n");
318 * Discard a connection when we're done with it - maybe it can be
321 public void discardConnection(UnicastConnection conn
) {
322 //System.out.println("Discarding connection " + conn);
324 if (ssock
!= null) //server connection
327 // To client connection, we'd like to return back to pool
328 UnicastConnection
.resetTime(conn
);
329 //Ensure there're only one scavenger globally
330 synchronized(GLOBAL_LOCK
) {
331 connections
.add(conn
); //borrow this lock to garantee thread safety
332 if (scavenger
== null)
339 * Start a server on this manager if it's a server socket and we've not
340 * already got one running.
342 public void startServer() {
344 if (ssock
== null || serverThread
!= null) {
347 serverThread
= new Thread(this);
348 // The following is not necessary when java.lang.Thread's constructor do this.
349 // serverThread.setContextClassLoader(Thread.currentThread().getContextClassLoader());
351 serverThread
.start();
355 * Stop a server on this manager
357 public void stopServer() {
359 if(serverThread
!= null){
363 }catch(Exception _
){}
369 * Server thread for connection manager.
372 for (;serverThread
!= null;) { // if serverThread==null, then exit thread
374 //System.out.println("Waiting for connection on " + serverPort);
375 UnicastConnection conn
= getServerConnection();
376 // use a thread pool to improve performance
377 //ConnectionRunnerPool.dispatchConnection(conn);
378 (new Thread(conn
)).start();
380 catch (Exception e
) {
387 * Serialization routine.
389 void write(ObjectOutput out
) throws IOException
{
390 out
.writeUTF(serverName
);
391 out
.writeInt(serverPort
);
395 * Serialization routine.
397 static UnicastConnectionManager
read(ObjectInput in
) throws IOException
{
398 String host
= in
.readUTF();
399 int port
= in
.readInt();
400 //RMIClientSocketFactory csf = ((RMIObjectInputStream)in).manager.clientFactory;
401 //return (getInstance(host, port, csf));
402 return (getInstance(host
, port
, null));
408 * This is use as the hashkey for the client/server connections.
416 TripleKey(String host
, int port
, Object other
) {
423 * Hash code just include the host and other - we ignore the port since
424 * this has unusual matching behaviour.
426 public int hashCode() {
427 return (host
.hashCode() ^ other
.hashCode());
430 public boolean equals(Object obj
) {
431 if (obj
instanceof TripleKey
) {
432 TripleKey other
= (TripleKey
)obj
;
433 if (this.host
.equals(other
.host
) &&
434 this.other
== other
.other
&&
435 (this.port
== other
.port
/* || this.port == 0 || other.port == 0*/)) {