KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > util > PortChooser


1 /**
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.util;
5
6 import com.tc.net.EphemeralPorts;
7 import com.tc.net.EphemeralPorts.Range;
8
9 import java.io.IOException JavaDoc;
10 import java.net.BindException JavaDoc;
11 import java.net.ServerSocket JavaDoc;
12 import java.util.HashSet JavaDoc;
13 import java.util.Random JavaDoc;
14 import java.util.Set JavaDoc;
15
16 public final class PortChooser {
17   private static final Object JavaDoc VM_WIDE_LOCK = (PortChooser.class.getName() + "LOCK").intern();
18   private static final Set JavaDoc chosen = new HashSet JavaDoc();
19   private static final Random JavaDoc random = new Random JavaDoc();
20   private static final Range exclude = EphemeralPorts.getRange();
21
22   public int chooseRandomPort() {
23     synchronized (VM_WIDE_LOCK) {
24       return choose();
25     }
26   }
27
28   private int choose() {
29     while (true) {
30       final Integer JavaDoc attempt = new Integer JavaDoc(getNonEphemeralPort());
31       boolean added = chosen.add(attempt);
32       if (!added) {
33         continue; // already picked at some point, try again
34
}
35
36       ServerSocket JavaDoc ss = null;
37       try {
38         int port = attempt.intValue();
39         ss = new ServerSocket JavaDoc(port);
40         return port;
41       } catch (BindException JavaDoc be) {
42         continue; // port in use, try another
43
} catch (IOException JavaDoc e) {
44         throw new RuntimeException JavaDoc(e);
45       } finally {
46         if (ss != null) {
47           while (!ss.isClosed()) {
48             try {
49               ss.close();
50             } catch (IOException JavaDoc e) {
51               // ignore
52
}
53           }
54         }
55       }
56     }
57   }
58
59   private static int getNonEphemeralPort() {
60     while (true) {
61       int p = random.nextInt(65535 - 1024) + 1024;
62       if (p < exclude.getLower() || p > exclude.getUpper()) { return p; }
63     }
64   }
65
66 }
67
Popular Tags