2 Replies Latest reply: Feb 8, 2012 9:09 PM by qiao RSS

    Is this caused by JIT optimize?

    qiao
      hi,guys.
      Recently,i wrote some code using CountDownLatch.I thought the "timeTask" method would return a number bigger than 100,but actually it will return some number litter than 100 sometimes. how to explain this,is caused by JIT optimize?Thank you for your help。
      import java.util.concurrent.CountDownLatch;
      
      public class CountDownLatchDemo {
           
           public long timeTask(Runnable[] sources) throws InterruptedException{
                final CountDownLatch start = new CountDownLatch(1);
               final CountDownLatch end = new CountDownLatch(sources.length);
                for(final Runnable source:sources){
                     Thread t = new Thread(){
                          public void run(){
                               try {
                                    start.await();
                                    try{
                                         source.run();
                                    }finally{
                                         end.countDown();
                                    }
                               } catch (InterruptedException e) {
                                    e.printStackTrace();
                               }
                          }
                     };
                     t.start();
                }
                synchronized (this) {
                     long start_t=System.currentTimeMillis();
                     start.countDown();
                     end.await();
                     long end_t = System.currentTimeMillis();
                     long gap = end_t-start_t;
                     System.out.println("the last gap is "+gap);
                     return gap;
                }
           }
           
           public static void main(String[] args) {
                Runnable[] sources = new Runnable[10];
                for(int i = 0;i<sources.length;i++){
                     final int index = i;
                     sources[i] = new Runnable() {
                          public void run() {
                               try {
                                    Thread.sleep(100);
                                    System.out.println("current thread is ["+index+"]");
                               } catch (InterruptedException e) {
                                    e.printStackTrace();
                               }
                               
                          }
                     };
                }
                try {
                     new CountDownLatchDemo().timeTask(sources);
                } catch (InterruptedException e) {
                     e.printStackTrace();
                }
           }
      }