Home | History | Annotate | Download | only in src
      1 // Copyright 2007 The Android Open Source Project
      2 
      3 /**
      4  * Exercise Object.wait(), comparing results against wall clock time.
      5  */
      6 public class Main {
      7     /* delays, in milliseconds */
      8     private final static long[] DELAYS = {
      9         200, 500, 1000, 2000, 3500, 8000
     10     };
     11 
     12     public static void main(String[] args) {
     13         boolean timing = (args.length >= 1) && args[0].equals("--timing");
     14         doit(timing);
     15     }
     16 
     17     public static void doit(boolean timing) {
     18         Object sleepy = new Object();
     19         long start, end;
     20 
     21         synchronized (sleepy) {
     22             try {
     23                 sleepy.wait(-500);
     24                 System.out.println("HEY: didn't throw on negative arg");
     25             } catch (IllegalArgumentException iae) {
     26                 System.out.println("Caught expected exception on neg arg");
     27             } catch (InterruptedException ie) {
     28                 ie.printStackTrace();
     29             }
     30 
     31             for(long delay : DELAYS) {
     32                 System.out.println("Waiting for " + delay + "ms...");
     33 
     34                 start = System.currentTimeMillis();
     35                 try {
     36                     sleepy.wait(delay);
     37                 } catch (InterruptedException ie) {
     38                     ie.printStackTrace();
     39                 }
     40                 end = System.currentTimeMillis();
     41 
     42                 long elapsed = end - start;
     43                 boolean showTime = timing;
     44 
     45                 if (! timing) {
     46                     long epsilon = delay / 10;
     47                     if (epsilon > 50) {
     48                         epsilon = 50;
     49                     }
     50 
     51                     long min = delay - epsilon;
     52                     long max = delay + epsilon;
     53 
     54                     if (elapsed < min) {
     55                         System.out.println("  Elapsed time was too short");
     56                         showTime = true;
     57                     } else if (elapsed > max) {
     58                         System.out.println("  Elapsed time was too long: "
     59                             + "elapsed=" + elapsed + " max=" + max);
     60                         showTime = true;
     61                     }
     62                 }
     63 
     64                 if (showTime) {
     65                     System.out.println("  Wall clock elapsed "
     66                             + elapsed + "ms");
     67                 }
     68             }
     69         }
     70     }
     71 }
     72