001 /* 002 * Copyright 2011 Christian Kumpe http://kumpe.de/christian/java 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 package de.kumpe.hadooptimizer.examples.analysis; 017 018 import java.io.FileNotFoundException; 019 import java.io.PrintWriter; 020 import java.util.Random; 021 import java.util.concurrent.BrokenBarrierException; 022 import java.util.concurrent.CyclicBarrier; 023 024 public class Polling { 025 private Random random = new Random(); 026 private CyclicBarrier barrier = new CyclicBarrier(3); 027 private volatile boolean waitingFinished; 028 private volatile boolean polling3Finished; 029 030 private class Polling3 extends Thread { 031 @Override 032 public void run() { 033 try { 034 barrier.await(); 035 while (!waitingFinished) { 036 Thread.sleep(300 + Math.round(random.nextGaussian())); 037 } 038 polling3Finished = true; 039 } catch (final InterruptedException e) { 040 e.printStackTrace(); 041 } catch (final BrokenBarrierException e) { 042 e.printStackTrace(); 043 } 044 } 045 } 046 047 private class Waiting extends Thread { 048 long sleep; 049 050 public Waiting(final long sleep) { 051 this.sleep = sleep; 052 } 053 054 @Override 055 public void run() { 056 try { 057 barrier.await(); 058 Thread.sleep(sleep); 059 waitingFinished = true; 060 } catch (final InterruptedException e) { 061 e.printStackTrace(); 062 } catch (final BrokenBarrierException e) { 063 e.printStackTrace(); 064 } 065 } 066 } 067 068 public Polling() { 069 try { 070 final PrintWriter out = new PrintWriter("/tmp/test.out"); 071 for (int time = 0; time < 10000; time++) { 072 waitingFinished = false; 073 polling3Finished = false; 074 new Polling3().start(); 075 new Waiting(time * time).start(); 076 barrier.await(); 077 final long start = System.currentTimeMillis(); 078 while (!polling3Finished) { 079 Thread.sleep(100 + Math.round(random.nextGaussian())); 080 } 081 final long now = System.currentTimeMillis(); 082 System.out.printf("Round %d took %dms.%n", time, now - start); 083 out.print(time * time); 084 out.print('\t'); 085 out.println(now - start); 086 out.flush(); 087 } 088 } catch (final InterruptedException e) { 089 e.printStackTrace(); 090 } catch (final BrokenBarrierException e) { 091 e.printStackTrace(); 092 } catch (final FileNotFoundException e) { 093 e.printStackTrace(); 094 } 095 } 096 097 public static void main(final String[] args) { 098 new Polling(); 099 } 100 }