1 7 package java.rmi.server; 8 9 import java.io.DataInput ; 10 import java.io.DataOutput ; 11 import java.io.EOFException ; 12 import java.io.IOException ; 13 import java.io.InputStream ; 14 import java.io.OutputStream ; 15 import java.security.SecureRandom ; 16 17 56 public final class UID implements java.io.Serializable { 57 58 private static final long ONE_SECOND = 1000; private static int hostUnique; 60 private static boolean hostUniqueSet = false; 61 62 private static final Object lock = new Object (); 63 private static long lastTime = System.currentTimeMillis(); 64 private static short lastCount = Short.MIN_VALUE; 65 66 67 private static final long serialVersionUID = 1086053664494604050L; 68 69 74 private final int unique; 75 76 81 private final long time; 82 83 88 private final short count; 89 90 94 public UID() { 95 96 synchronized (lock) { 97 if (!hostUniqueSet) { 98 hostUnique = (new SecureRandom ()).nextInt(); 99 hostUniqueSet = true; 100 } 101 unique = hostUnique; 102 if (lastCount == Short.MAX_VALUE) { 103 boolean done = false; 104 while (!done) { 105 long now = System.currentTimeMillis(); 106 if (now < lastTime + ONE_SECOND) { 107 try { 109 Thread.currentThread().sleep(ONE_SECOND); 110 } catch (java.lang.InterruptedException e) { 111 } continue; 113 } else { 114 lastTime = now; 115 lastCount = Short.MIN_VALUE; 116 done = true; 117 } 118 } 119 } 120 time = lastTime; 121 count = lastCount++; 122 } 123 } 124 125 136 public UID(short num) { 137 unique = 0; 138 time = 0; 139 count = num; 140 } 141 142 145 private UID(int unique, long time, short count) { 146 this.unique = unique; 147 this.time = time; 148 this.count = count; 149 } 150 151 156 public int hashCode() { 157 return (int) time + (int) count; 158 } 159 160 174 public boolean equals(Object obj) { 175 if (obj instanceof UID ) { 176 UID uid = (UID )obj; 177 return (unique == uid.unique && 178 count == uid.count && 179 time == uid.time); 180 } else { 181 return false; 182 } 183 } 184 185 190 public String toString() { 191 return Integer.toString(unique,16) + ":" + 192 Long.toString(time,16) + ":" + 193 Integer.toString(count,16); 194 } 195 196 214 public void write(DataOutput out) throws IOException { 215 out.writeInt(unique); 216 out.writeLong(time); 217 out.writeShort(count); 218 } 219 220 243 public static UID read(DataInput in) throws IOException { 244 int unique = in.readInt(); 245 long time = in.readLong(); 246 short count = in.readShort(); 247 return new UID (unique, time, count); 248 } 249 } 250 | Popular Tags |