Example usage for java.util.concurrent Exchanger Exchanger

List of usage examples for java.util.concurrent Exchanger Exchanger

Introduction

In this page you can find the example usage for java.util.concurrent Exchanger Exchanger.

Prototype

public Exchanger() 

Source Link

Document

Creates a new Exchanger.

Usage

From source file:ExgrDemo.java

public static void main(String args[]) {
    Exchanger<String> exgr = new Exchanger<String>();

    new UseString(exgr);
    new MakeString(exgr);
}

From source file:ExchangerProducer.java

public static void main(String[] args) {
    Exchanger<ArrayList<Integer>> exchanger = new Exchanger<>();
    ExchangerProducer producer = new ExchangerProducer(exchanger);
    ExchangerConsumer consumer = new ExchangerConsumer(exchanger);
    producer.start();/* ww  w. j a  v a  2s . c  o m*/
    consumer.start();
}

From source file:com.netflix.curator.framework.recipes.cache.TestNodeCache.java

@Test
public void testRebuildAgainstOtherProcesses() throws Exception {
    NodeCache cache = null;/* w w w. jav a2s  . c  o  m*/
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    client.start();
    try {
        client.create().forPath("/test");
        client.create().forPath("/test/snafu", "original".getBytes());

        final CountDownLatch latch = new CountDownLatch(1);
        cache = new NodeCache(client, "/test/snafu");
        cache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                latch.countDown();
            }
        });
        cache.rebuildTestExchanger = new Exchanger<Object>();

        ExecutorService service = Executors.newSingleThreadExecutor();
        final NodeCache finalCache = cache;
        Future<Object> future = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                finalCache.rebuildTestExchanger.exchange(new Object(), 10, TimeUnit.SECONDS);

                // simulate another process updating the node while we're rebuilding
                client.setData().forPath("/test/snafu", "other".getBytes());

                ChildData currentData = finalCache.getCurrentData();
                Assert.assertNotNull(currentData);

                finalCache.rebuildTestExchanger.exchange(new Object(), 10, TimeUnit.SECONDS);

                return null;
            }
        });
        cache.start(false);
        future.get();

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
        Assert.assertNotNull(cache.getCurrentData());
        Assert.assertEquals(cache.getCurrentData().getData(), "other".getBytes());
    } finally {
        IOUtils.closeQuietly(cache);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.netflix.curator.framework.recipes.cache.TestPathChildrenCache.java

@Test
public void testRebuildAgainstOtherProcesses() throws Exception {
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    client.start();//w  w  w.  j  a  va  2 s. co  m
    try {
        client.create().forPath("/test");
        client.create().forPath("/test/foo");
        client.create().forPath("/test/bar");
        client.create().forPath("/test/snafu", "original".getBytes());

        final CountDownLatch addedLatch = new CountDownLatch(2);
        final PathChildrenCache cache = new PathChildrenCache(client, "/test", true);
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) {
                    if (event.getData().getPath().equals("/test/test")) {
                        addedLatch.countDown();
                    }
                } else if (event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED) {
                    if (event.getData().getPath().equals("/test/snafu")) {
                        addedLatch.countDown();
                    }
                }
            }
        });
        cache.rebuildTestExchanger = new Exchanger<Object>();
        ExecutorService service = Executors.newSingleThreadExecutor();
        final AtomicReference<String> deletedPath = new AtomicReference<String>();
        Future<Object> future = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                cache.rebuildTestExchanger.exchange(new Object());

                // simulate another process adding a node while we're rebuilding
                client.create().forPath("/test/test");

                List<ChildData> currentData = cache.getCurrentData();
                Assert.assertTrue(currentData.size() > 0);

                // simulate another process removing a node while we're rebuilding
                client.delete().forPath(currentData.get(0).getPath());
                deletedPath.set(currentData.get(0).getPath());

                cache.rebuildTestExchanger.exchange(new Object());

                ChildData childData = null;
                while (childData == null) {
                    childData = cache.getCurrentData("/test/snafu");
                    Thread.sleep(1000);
                }
                Assert.assertEquals(childData.getData(), "original".getBytes());
                client.setData().forPath("/test/snafu", "grilled".getBytes());

                cache.rebuildTestExchanger.exchange(new Object());

                return null;
            }
        });
        cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
        future.get();

        Assert.assertTrue(addedLatch.await(10, TimeUnit.SECONDS));
        Assert.assertNotNull(cache.getCurrentData("/test/test"));
        Assert.assertNull(cache.getCurrentData(deletedPath.get()));
        Assert.assertEquals(cache.getCurrentData("/test/snafu").getData(), "grilled".getBytes());

        cache.close();
    } finally {
        client.close();
    }
}

From source file:com.streamsets.datacollector.execution.runner.common.TestProductionPipeline.java

@Test
public void testRateLimit() throws Exception {
    final TestProducer p = new TestProducer();
    MockStages.setSourceCapture(p);//  ww  w .  j a va  2 s .c  o  m

    final ProductionPipeline pipeline = createProductionPipeline(DeliveryGuarantee.AT_MOST_ONCE, true, 10L,
            false/*source not committer*/);
    pipeline.registerStatusListener(new MyStateListener());
    final Exchanger<Double> rate = new Exchanger<>();
    new Thread() {
        @Override
        public void run() {
            try {
                long start = System.nanoTime();
                pipeline.run();
                rate.exchange(p.count.doubleValue() * 1000 * 1000 * 1000 / (System.nanoTime() - start));
            } catch (Exception ex) {

            }
        }
    }.start();
    Thread.sleep(10000);
    pipeline.stop();
    Double rateAchieved = rate.exchange(0.0);
    // To account for the slight loss of precision, we compare the "long-ified" versions.
    Assert.assertTrue(rateAchieved.longValue() <= 10);
}

From source file:org.jdesktop.swingworker.AccumulativeRunnable.java

public final void testPublishAndProcess() throws Exception {
    final Exchanger<List<Integer>> listExchanger = 
        new Exchanger<List<Integer>>();
    final Exchanger<Boolean> boolExchanger = 
        new Exchanger<Boolean>();
    SwingWorker<List<Integer>,Integer> test = 
        new SwingWorker<List<Integer>, Integer>() {
            List<Integer> receivedArgs = 
                Collections.synchronizedList(new ArrayList<Integer>());
            Boolean isOnEDT = Boolean.TRUE;
            final int NUMBERS = 100;
            @Override//from   www  .  j  av a  2  s  . c  om
            protected List<Integer> doInBackground() throws Exception {
                List<Integer> ret = 
                    Collections.synchronizedList(
                        new ArrayList<Integer>(NUMBERS));
                for (int i = 0; i < NUMBERS; i++) {
                    publish(i);
                    ret.add(i);
                }
                return ret;
            }
            @Override
            protected void process(List<Integer> args) {
                for(Integer i : args) {
                    receivedArgs.add(i);
                }
                isOnEDT = isOnEDT && SwingUtilities.isEventDispatchThread();
                if (receivedArgs.size() == NUMBERS) {
                    try {
                        boolExchanger.exchange(isOnEDT);
                        listExchanger.exchange(receivedArgs);
                    } catch (InterruptedException ignore) {
                        ignore.printStackTrace();
                    }
                }
            }
    };
    test.execute();
    assertTrue(boolExchanger.exchange(null, TIME_OUT, TIME_OUT_UNIT));
    assertEquals(test.get(TIME_OUT, TIME_OUT_UNIT), 
        listExchanger.exchange(null, TIME_OUT, TIME_OUT_UNIT));
}

From source file:org.jdesktop.swingworker.AccumulativeRunnable.java

public final void testDone() throws Exception {
    final String testString  = "test"; 
    final Exchanger<Boolean> exchanger = new Exchanger<Boolean>();
    SwingWorker<?,?> test = new SwingWorker<String, Object>() {
        @Override/*  w w  w.j av  a 2  s.com*/
        protected String doInBackground() throws Exception {
            return testString;
        }
        @Override
        protected void done() {
            try {
                exchanger.exchange(
                    testString == get()
                    && SwingUtilities.isEventDispatchThread());
            } catch (Exception ignore) {
            }
        }
    };
    test.execute();
    assertTrue(exchanger.exchange(null, TIME_OUT, TIME_OUT_UNIT));
}

From source file:org.jdesktop.swingworker.AccumulativeRunnable.java

public final void testPropertyChange() throws Exception {
    final Exchanger<Boolean> boolExchanger = 
        new Exchanger<Boolean>();
    final SwingWorker<?,?> test = 
        new SwingWorker<Object, Object>() {
            @Override/* ww w  .j  a  v  a2s. co m*/
            protected Object doInBackground() throws Exception {
                firePropertyChange("test", null, "test");
                return null;
            }
        };
    test.addPropertyChangeListener(
        new PropertyChangeListener() {
            boolean isOnEDT = true;

            public  void propertyChange(PropertyChangeEvent evt) {
                isOnEDT &= SwingUtilities.isEventDispatchThread();
                if ("state".equals(evt.getPropertyName())
                    && StateValue.DONE == evt.getNewValue()) {
                    try {
                        boolExchanger.exchange(isOnEDT);
                    } catch (Exception ignore) {
                        ignore.printStackTrace();
                    }
                }
            }
        });
    test.execute();
    assertTrue(boolExchanger.exchange(null, TIME_OUT, TIME_OUT_UNIT));
}

From source file:org.jdesktop.swingworker.AccumulativeRunnable.java

public final void testWorkFlow() throws Exception {
    final List<Object> goldenSequence = 
        Arrays.asList(new Object[]{StateValue.STARTED, "done", 
                                   StateValue.DONE});
    final List<Object> sequence = 
                Collections.synchronizedList(new ArrayList<Object>());

    final Exchanger<List<Object>> listExchanger = new Exchanger<List<Object>>();
        // w ww  .j ava 2  s  .  co m
    final SwingWorker<?,?> test = 
        new SwingWorker<Object,Object>() {
            @Override
            protected Object doInBackground() throws Exception {
                return null;
            }
            @Override
            protected void done() {
                sequence.add("done");
            }
        };
    test.addPropertyChangeListener(
        new PropertyChangeListener() {
            public  void propertyChange(PropertyChangeEvent evt) {
                if ("state".equals(evt.getPropertyName())) {
                    sequence.add(evt.getNewValue());
                    if (StateValue.DONE == evt.getNewValue()) {
                        try {
                            listExchanger.exchange(sequence);
                        } catch (Exception ignore) {
                            ignore.printStackTrace();
                        }
                    }
                }
            }
        });
    test.execute();
    assertEquals(goldenSequence, 
                 listExchanger.exchange(null, TIME_OUT, TIME_OUT_UNIT));
}

From source file:org.jdesktop.swingworker.AccumulativeRunnable.java

public final void test6493680() throws Exception {
    final AtomicInteger lastProgressValue = new AtomicInteger(-1);
    final Exchanger<Boolean> exchanger = new Exchanger<Boolean>();
    class Test {//from   w w  w  . j  a  va  2s  .c o m
        private final AtomicInteger lastProgressValue = 
            new AtomicInteger(-1);
        private final Exchanger<Boolean> exchanger = 
            new Exchanger<Boolean>();

        boolean test() throws Exception {
            TestSwingWorker swingWorker = new TestSwingWorker();
            swingWorker.addPropertyChangeListener(
                new PropertyChangeListener() {
                    public void propertyChange(PropertyChangeEvent evt) {
                        if ("progress" == evt.getPropertyName()) {
                            lastProgressValue.set((Integer) evt.getNewValue());
                        }
                    }
                });

            swingWorker.execute();
            return exchanger.exchange(true);
        }

        class TestSwingWorker extends SwingWorker<Void, Void> {
            @Override
            protected Void doInBackground() throws Exception {
                for (int i = 0; i <= 100; i++) {
                    Thread.sleep(1);
                    setProgress(i);
                }
                return null;
            }
            @Override
            protected void done() {
                boolean isPassed = (lastProgressValue.get() == 100);
                try {
                    exchanger.exchange(isPassed);
                } catch (Exception ingore) {
                }
            }
        }
    }
    /*
     * because timing is involved in this bug we will run the test
     * NUMBER_OF_TRIES times.
     * the tes`t passes if it does not fail once.
     */
     final int NUMBER_OF_TRIES = 50;
     for (int i = 0; i < NUMBER_OF_TRIES; i++) {
         assertTrue((new Test()).test());
     }
}