FSF GCC merge 02/23/03
[official-gcc.git] / libjava / gnu / java / rmi / server / UnicastConnectionManager.java
blobd54dcf1d4cd654d2619f419bd49e6a0d00ce13bb
1 /*
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)
9 any later version.
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
19 02111-1307 USA.
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
24 combination.
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;
75 String serverName;
76 int serverPort;
78 static private 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 scavenger.start();
159 * Client UnicastConnectionManager constructor
161 private UnicastConnectionManager(String host, int port, RMIClientSocketFactory csf) {
162 ssock = null;
163 serverName = host;
164 serverPort = port;
165 serverFactory = null;
166 clientFactory = csf;
167 connections = new ArrayList();
171 * Server UnicastConnectionManager constructor
173 private UnicastConnectionManager(int port, RMIServerSocketFactory ssf) {
174 try {
175 ssock = ssf.createServerSocket(port);
176 serverPort = ssock.getLocalPort();
178 catch (IOException _) {
179 try {
180 ssock = ssf.createServerSocket(0);
181 serverPort = ssock.getLocalPort();
183 catch (IOException __) {
184 ssock = null;
185 serverPort = 0;
188 serverName = localhost;
189 serverFactory = ssf;
190 clientFactory = null;
194 * Return a client connection manager which will connect to the given
195 * host/port.
197 public static synchronized UnicastConnectionManager getInstance(String host, int port, RMIClientSocketFactory csf) {
198 //System.out.println("getInstance: " + host + "," + port + "," + csf);
199 if (csf == null) {
200 csf = defaultSocketFactory;
202 // change host name to host address to avoid name resolving issues
203 try{
204 host = InetAddress.getByName(host).getHostAddress();
205 }catch(Exception _){}
207 TripleKey key = new TripleKey(host, port, csf);
208 UnicastConnectionManager man = (UnicastConnectionManager)clients.get(key);
209 if (man == null) {
210 man = new UnicastConnectionManager(host, port, csf);
211 if (debug) {
212 ncmanager++;
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;
223 return (man);
227 * Return a server connection manager which will accept connection on the
228 * given port.
230 public static synchronized UnicastConnectionManager getInstance(int port, RMIServerSocketFactory ssf) {
231 //System.out.println("getInstance: " + port + "," + ssf);
232 if (ssf == null) {
233 ssf = defaultSocketFactory;
235 TripleKey key = new TripleKey(localhost, port, ssf);
236 UnicastConnectionManager man = (UnicastConnectionManager)servers.get(key);
237 if (man == null) {
238 man = new UnicastConnectionManager(port, ssf);
239 if (debug) {
240 nsmanager++;
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);
247 return (man);
251 * Get a connection from this manager.
253 public UnicastConnection getConnection() throws IOException {
254 if (ssock == null) {
255 return (getClientConnection());
257 else {
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();
270 if (debug){
271 nssock++;
272 System.out.println("\n\n ****** " + nssock + " server socks.\n\n");
274 //System.out.println("Server connection " + sock);
275 return (conn);
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
289 if(nconn >= 0) {
290 conn = (UnicastConnection)conns.get(nconn);
291 //Should we check if conn is alive using Ping??
292 conns.remove(nconn);
294 // Check if the connection is already expired
295 long l = System.currentTimeMillis();
296 if (!UnicastConnection.isExpired(conn, l)){
297 return conn;
298 }else {
299 conn.disconnect();
300 conn = null;
305 Socket sock = clientFactory.createSocket(serverName, serverPort);
306 conn = new UnicastConnection(this, sock);
307 conn.makeConnection(DEFAULT_PROTOCOL);
309 if (debug) {
310 ncsock++;
311 System.out.println("\n\n ====== " + ncsock + " client socks.\n\n");
314 return (conn);
318 * Discard a connection when we're done with it - maybe it can be
319 * recycled.
321 public void discardConnection(UnicastConnection conn) {
322 //System.out.println("Discarding connection " + conn);
323 //conn.disconnect();
324 if (ssock != null) //server connection
325 conn.disconnect();
326 else {
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)
333 startScavenger();
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() {
343 synchronized(this) {
344 if (ssock == null || serverThread != null) {
345 return;
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() {
358 synchronized(this) {
359 if(serverThread != null){
360 serverThread = null;
361 try{
362 ssock.close();
363 }catch(Exception _){}
369 * Server thread for connection manager.
371 public void run() {
372 for (;serverThread != null;) { // if serverThread==null, then exit thread
373 try {
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) {
381 e.printStackTrace();
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.
410 class TripleKey {
412 String host;
413 int port;
414 Object other;
416 TripleKey(String host, int port, Object other) {
417 this.host = host;
418 this.port = port;
419 this.other = 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*/)) {
436 return (true);
439 return (false);