util.java
来自「JGRoups源码」· Java 代码 · 共 2,058 行 · 第 1/5 页
JAVA
2,058 行
public static void sleep(long timeout, int nanos) { try { Thread.sleep(timeout, nanos); } catch(Throwable e) { } } /** * On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will * sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the * thread never relinquishes control and therefore the sleep(x) is exactly x ms long. */ public static void sleep(long msecs, boolean busy_sleep) { if(!busy_sleep) { sleep(msecs); return; } long start=System.currentTimeMillis(); long stop=start + msecs; while(stop > start) { start=System.currentTimeMillis(); } } /** Returns a random value in the range [1 - range] */ public static long random(long range) { return (long)((Math.random() * 100000) % range) + 1; } /** Sleeps between 1 and timeout milliseconds, chosen randomly. Timeout must be > 1 */ public static void sleepRandom(long timeout) { if(timeout <= 0) { return; } long r=(int)((Math.random() * 100000) % timeout) + 1; sleep(r); } /** Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8, chances are that in 80% of all cases, true will be returned and false in 20%. */ public static boolean tossWeightedCoin(double probability) { long r=random(100); long cutoff=(long)(probability * 100); return r < cutoff; } public static String getHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch(Exception ex) { } return "localhost"; } public static void dumpStack(boolean exit) { try { throw new Exception("Dumping stack:"); } catch(Exception e) { e.printStackTrace(); if(exit) System.exit(0); } } /** * Debugging method used to dump the content of a protocol queue in a condensed form. Useful * to follow the evolution of the queue's content in time. */ public static String dumpQueue(Queue q) { StringBuffer sb=new StringBuffer(); LinkedList values=q.values(); if(values.size() == 0) { sb.append("empty"); } else { for(Iterator it=values.iterator(); it.hasNext();) { Object o=it.next(); String s=null; if(o instanceof Event) { Event event=(Event)o; int type=event.getType(); s=Event.type2String(type); if(type == Event.VIEW_CHANGE) s+=" " + event.getArg(); if(type == Event.MSG) s+=" " + event.getArg(); if(type == Event.MSG) { s+="["; Message m=(Message)event.getArg(); Map headers=m.getHeaders(); for(Iterator i=headers.keySet().iterator(); i.hasNext();) { Object headerKey=i.next(); Object value=headers.get(headerKey); String headerToString=null; if(value instanceof FD.FdHeader) { headerToString=value.toString(); } else if(value instanceof PingHeader) { headerToString=headerKey + "-"; if(((PingHeader)value).type == PingHeader.GET_MBRS_REQ) { headerToString+="GMREQ"; } else if(((PingHeader)value).type == PingHeader.GET_MBRS_RSP) { headerToString+="GMRSP"; } else { headerToString+="UNKNOWN"; } } else { headerToString=headerKey + "-" + (value == null ? "null" : value.toString()); } s+=headerToString; if(i.hasNext()) { s+=","; } } s+="]"; } } else { s=o.toString(); } sb.append(s).append("\n"); } } return sb.toString(); } /** * Use with caution: lots of overhead */ public static String printStackTrace(Throwable t) { StringWriter s=new StringWriter(); PrintWriter p=new PrintWriter(s); t.printStackTrace(p); return s.toString(); } public static String getStackTrace(Throwable t) { return printStackTrace(t); } public static String print(Throwable t) { return printStackTrace(t); } public static void crash() { System.exit(-1); } public static String printEvent(Event evt) { Message msg; if(evt.getType() == Event.MSG) { msg=(Message)evt.getArg(); if(msg != null) { if(msg.getLength() > 0) return printMessage(msg); else return msg.printObjectHeaders(); } } return evt.toString(); } /** Tries to read an object from the message's buffer and prints it */ public static String printMessage(Message msg) { if(msg == null) return ""; if(msg.getLength() == 0) return null; try { return msg.getObject().toString(); } catch(Exception e) { // it is not an object return ""; } } /** Tries to read a <code>MethodCall</code> object from the message's buffer and prints it. Returns empty string if object is not a method call */ public static String printMethodCall(Message msg) { Object obj; if(msg == null) return ""; if(msg.getLength() == 0) return ""; try { obj=msg.getObject(); return obj.toString(); } catch(Exception e) { // it is not an object return ""; } } public static void printThreads() { Thread threads[]=new Thread[Thread.activeCount()]; Thread.enumerate(threads); System.out.println("------- Threads -------"); for(int i=0; i < threads.length; i++) { System.out.println("#" + i + ": " + threads[i]); } System.out.println("------- Threads -------\n"); } public static String activeThreads() { StringBuffer sb=new StringBuffer(); Thread threads[]=new Thread[Thread.activeCount()]; Thread.enumerate(threads); sb.append("------- Threads -------\n"); for(int i=0; i < threads.length; i++) { sb.append("#").append(i).append(": ").append(threads[i]).append('\n'); } sb.append("------- Threads -------\n"); return sb.toString(); } public static String printBytes(long bytes) { double tmp; if(bytes < 1000) return bytes + "b"; if(bytes < 1000000) { tmp=bytes / 1000.0; return f.format(tmp) + "KB"; } if(bytes < 1000000000) { tmp=bytes / 1000000.0; return f.format(tmp) + "MB"; } else { tmp=bytes / 1000000000.0; return f.format(tmp) + "GB"; } } public static String printBytes(double bytes) { double tmp; if(bytes < 1000) return bytes + "b"; if(bytes < 1000000) { tmp=bytes / 1000.0; return f.format(tmp) + "KB"; } if(bytes < 1000000000) { tmp=bytes / 1000000.0; return f.format(tmp) + "MB"; } else { tmp=bytes / 1000000000.0; return f.format(tmp) + "GB"; } } /** Fragments a byte buffer into smaller fragments of (max.) frag_size. Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments of 248 bytes each and 1 fragment of 32 bytes. @return An array of byte buffers (<code>byte[]</code>). */ public static byte[][] fragmentBuffer(byte[] buf, int frag_size, final int length) { byte[] retval[]; int accumulated_size=0; byte[] fragment; int tmp_size=0; int num_frags; int index=0; num_frags=length % frag_size == 0 ? length / frag_size : length / frag_size + 1; retval=new byte[num_frags][]; while(accumulated_size < length) { if(accumulated_size + frag_size <= length) tmp_size=frag_size; else tmp_size=length - accumulated_size; fragment=new byte[tmp_size]; System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size); retval[index++]=fragment; accumulated_size+=tmp_size; } return retval; } public static byte[][] fragmentBuffer(byte[] buf, int frag_size) { return fragmentBuffer(buf, frag_size, buf.length); } /** * Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and * return them in a list. Example:<br/> * Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}). * This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment * starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length * of 2 bytes. * @param frag_size * @return List. A List<Range> of offset/length pairs */ public static java.util.List computeFragOffsets(int offset, int length, int frag_size) { java.util.List retval=new ArrayList(); long total_size=length + offset; int index=offset; int tmp_size=0; Range r; while(index < total_size) { if(index + frag_size <= total_size) tmp_size=frag_size; else tmp_size=(int)(total_size - index); r=new Range(index, tmp_size); retval.add(r); index+=tmp_size; } return retval; } public static java.util.List computeFragOffsets(byte[] buf, int frag_size) { return computeFragOffsets(0, buf.length, frag_size); } /** Concatenates smaller fragments into entire buffers. @param fragments An array of byte buffers (<code>byte[]</code>) @return A byte buffer */ public static byte[] defragmentBuffer(byte[] fragments[]) { int total_length=0; byte[] ret; int index=0; if(fragments == null) return null; for(int i=0; i < fragments.length; i++) { if(fragments[i] == null) continue; total_length+=fragments[i].length; } ret=new byte[total_length]; for(int i=0; i < fragments.length; i++) { if(fragments[i] == null) continue; System.arraycopy(fragments[i], 0, ret, index, fragments[i].length); index+=fragments[i].length; } return ret; } public static void printFragments(byte[] frags[]) { for(int i=0; i < frags.length; i++) System.out.println('\'' + new String(frags[i]) + '\''); }// /**// Peeks for view on the channel until n views have been received or timeout has elapsed.// Used to determine the view in which we want to start work. Usually, we start as only// member in our own view (1st view) and the next view (2nd view) will be the full view// of all members, or a timeout if we're the first member. If a non-view (a message or// block) is received, the method returns immediately.// @param channel The channel used to peek for views. Has to be operational.// @param number_of_views The number of views to wait for. 2 is a good number to ensure that,// if there are other members, we start working with them included in our view.// @param timeout Number of milliseconds to wait until view is forced to return. A value// of <= 0 means wait forever.// */// public static View peekViews(Channel channel, int number_of_views, long timeout) {// View retval=null;// Object obj=null;// int num=0;// long start_time=System.currentTimeMillis();
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?