Example usage for java.util.concurrent Executors callable

List of usage examples for java.util.concurrent Executors callable

Introduction

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

Prototype

public static <T> Callable<T> callable(Runnable task, T result) 

Source Link

Document

Returns a Callable object that, when called, runs the given task and returns the given result.

Usage

From source file:com.github.vatbub.tictactoe.view.AnimationThreadPoolExecutor.java

/**
 * @throws RejectedExecutionException {@inheritDoc}
 * @throws NullPointerException       {@inheritDoc}
 *///from   w w w . j a  va2  s  .c  o m
@NotNull
@Override
public <T> Future<T> submit(Runnable task, T result) {
    Runnable effectiveTask = () -> Platform.runLater(task);
    return super.schedule(Executors.callable(effectiveTask, result), 0, NANOSECONDS);
}

From source file:com.github.vatbub.tictactoe.view.AnimationThreadPoolExecutor.java

@SuppressWarnings("unused")
public <T> Future<T> submitWaitForUnlock(Runnable task, T result) {
    Runnable effectiveTask = createEffectiveWaitingTask(task);
    return super.schedule(Executors.callable(effectiveTask, result), 0, NANOSECONDS);
}

From source file:meme.singularsyntax.concurrency.ContinuableFutureTask.java

/**
 * Creates a <tt>ContinuableFutureTask</tt> that will, upon running, execute the
 * given <tt>Runnable</tt>, and arrange that <tt>get</tt> will return the
 * given result on successful completion.
 *
 * @param runnable the runnable task/* w  ww. j a va 2 s . c  o  m*/
 * @param result the result to return on successful completion. If
 * you don't need a particular result, consider using
 * constructions of the form:
 * <tt>Future&lt;?&gt; f = new ContinuableFutureTask&lt;Object&gt;(runnable, null)</tt>
 * @throws NullPointerException if runnable is null
 */
public ContinuableFutureTask(Runnable runnable, V result) {
    sync = new Sync(Executors.callable(runnable, result));
    task = Executors.callable(runnable, result);
}

From source file:com.twitter.graphjet.bipartite.edgepool.EdgePoolConcurrentTestHelper.java

/**
 * This helper method sets up a concurrent read-write situation with a single writer and multiple
 * readers that access the same underlying edgePool, and tests for correct edge access during
 * simultaneous edge writes. This helps test read consistency during arbitrary points of
 * inserting edges. Note that the exact read-write sequence here is non-deterministic and would
 * vary depending on the machine, but the hope is that given the large number of readers the reads
 * would be done at many different points of edge insertion. The test itself checks only for
 * partial correctness (it could have false positives) so this should only be used as a supplement
 * to other testing.// www  . j a  va  2s. c om
 *
 * @param edgePool           is the underlying
 *                           {@link com.twitter.graphjet.bipartite.edgepool.EdgePool}
 * @param numReadersPerNode  is the number of reader threads to use per node
 * @param leftSize           is the number of left nodes
 * @param rightSize          is the number of right nodes
 * @param edgeProbability    is the probability of an edge between a left-right node pair
 * @param random             is the random number generator to use for generating a random graph
 */
public static void testRandomConcurrentReadWriteThreads(EdgePool edgePool, int numReadersPerNode, int leftSize,
        int rightSize, double edgeProbability, Random random) {
    int maxWaitingTimeForThreads = 20; // in milliseconds
    int numReaders = leftSize * numReadersPerNode;
    CountDownLatch readersDoneLatch = new CountDownLatch(numReaders);
    // First, construct a random set of edges to insert in the graph
    Set<Pair<Integer, Integer>> edges = Sets
            .newHashSetWithExpectedSize((int) (leftSize * rightSize * edgeProbability));
    List<EdgePoolReader> readers = Lists.newArrayListWithCapacity(numReaders);
    Int2ObjectMap<IntSet> leftSideGraph = new Int2ObjectOpenHashMap<IntSet>(leftSize);
    int averageLeftDegree = (int) (rightSize * edgeProbability);
    for (int i = 0; i < leftSize; i++) {
        IntSet nodeEdges = new IntOpenHashSet(averageLeftDegree);
        for (int j = 0; j < rightSize; j++) {
            if (random.nextDouble() < edgeProbability) {
                nodeEdges.add(j);
                edges.add(Pair.of(i, j));
            }
        }
        leftSideGraph.put(i, nodeEdges);
    }

    // Create a bunch of leftReaders per node that'll read from the graph at random
    for (int i = 0; i < leftSize; i++) {
        for (int j = 0; j < numReadersPerNode; j++) {
            readers.add(new EdgePoolReader(edgePool, new CountDownLatch(0), readersDoneLatch, i,
                    random.nextInt(maxWaitingTimeForThreads)));
        }
    }

    // Create a single writer that will insert these edges in random order
    List<WriterInfo> writerInfo = Lists.newArrayListWithCapacity(edges.size());
    List<Pair<Integer, Integer>> edgesList = Lists.newArrayList(edges);
    Collections.shuffle(edgesList);
    CountDownLatch writerDoneLatch = new CountDownLatch(edgesList.size());
    for (Pair<Integer, Integer> edge : edgesList) {
        writerInfo.add(new WriterInfo(edge.getLeft(), edge.getRight(), new CountDownLatch(0), writerDoneLatch));
    }

    ExecutorService executor = Executors.newFixedThreadPool(numReaders + 1); // single writer
    List<Callable<Integer>> allThreads = Lists.newArrayListWithCapacity(numReaders + 1);
    // First, we add the writer
    allThreads.add(Executors.callable(new EdgePoolWriter(edgePool, writerInfo), 1));
    // then the readers
    for (int i = 0; i < numReaders; i++) {
        allThreads.add(Executors.callable(readers.get(i), 1));
    }
    // these will execute in some non-deterministic order
    Collections.shuffle(allThreads, random);

    // Wait for all the processes to finish
    try {
        List<Future<Integer>> results = executor.invokeAll(allThreads, 10, TimeUnit.SECONDS);
        for (Future<Integer> result : results) {
            assertTrue(result.isDone());
            assertEquals(1, result.get().intValue());
        }
    } catch (InterruptedException e) {
        throw new RuntimeException("Execution for a thread was interrupted: ", e);
    } catch (ExecutionException e) {
        throw new RuntimeException("Execution issue in an executor thread: ", e);
    }

    // confirm that these worked as expected
    try {
        readersDoneLatch.await();
        writerDoneLatch.await();
    } catch (InterruptedException e) {
        throw new RuntimeException("Execution for last reader was interrupted: ", e);
    }

    // Check that all readers' read info is consistent with the graph
    for (EdgePoolReader reader : readers) {
        IntSet expectedEdges = leftSideGraph.get(reader.queryNode);
        assertTrue(reader.getQueryNodeDegree() <= expectedEdges.size());
        if (reader.getQueryNodeDegree() == 0) {
            assertNull(reader.getQueryNodeEdges());
        } else {
            for (int edge : reader.getQueryNodeEdges()) {
                assertTrue(expectedEdges.contains(edge));
            }
        }
    }
}

From source file:com.twitter.graphjet.bipartite.GraphConcurrentTestHelper.java

/**
 * This helper method sets up a concurrent read-write situation with a single writer and multiple
 * readers that access the same underlying bipartiteGraph, and tests for correct edge access during
 * simultaneous edge writes. This helps test read consistency during arbitrary points of
 * inserting edges. Note that the exact read-write sequence here is non-deterministic and would
 * vary depending on the machine, but the hope is that given the large number of readers the reads
 * would be done at many different points of edge insertion. The test itself checks only for
 * partial correctness (it could have false positives) so this should only be used as a supplement
 * to other testing.// w ww . j av  a2  s . com
 *
 * @param graph              is the underlying
 *                           {@link BipartiteGraph}
 * @param numReadersPerNode  is the number of reader threads to use per node
 * @param leftSize           is the number of left nodes
 * @param rightSize          is the number of right nodes
 * @param edgeProbability    is the probability of an edge between a left-right node pair
 * @param random             is the random number generator to use for generating a random graph
 */
public static <T extends BipartiteGraph & DynamicBipartiteGraph> void testRandomConcurrentReadWriteThreads(
        T graph, int numReadersPerNode, int leftSize, int rightSize, double edgeProbability, Random random) {
    int maxWaitingTimeForThreads = 20; // in milliseconds
    int numLeftReaders = leftSize * numReadersPerNode;
    int numRightReaders = rightSize * numReadersPerNode;
    int totalNumReaders = numLeftReaders + numRightReaders;
    CountDownLatch readersDoneLatch = new CountDownLatch(totalNumReaders);
    // First, construct a random set of edges to insert in the graph
    Set<Pair<Long, Long>> edges = Sets
            .newHashSetWithExpectedSize((int) (leftSize * rightSize * edgeProbability));
    List<BipartiteGraphReader> leftReaders = Lists.newArrayListWithCapacity(numLeftReaders);
    List<BipartiteGraphReader> rightReaders = Lists.newArrayListWithCapacity(numRightReaders);
    Long2ObjectMap<LongSet> leftSideGraph = new Long2ObjectOpenHashMap<LongSet>(leftSize);
    Long2ObjectMap<LongSet> rightSideGraph = new Long2ObjectOpenHashMap<LongSet>(leftSize);
    int averageLeftDegree = (int) (rightSize * edgeProbability);
    for (int i = 0; i < leftSize; i++) {
        LongSet nodeEdges = new LongOpenHashSet(averageLeftDegree);
        for (int j = 0; j < rightSize; j++) {
            if (random.nextDouble() < edgeProbability) {
                nodeEdges.add(j);
                if (!rightSideGraph.containsKey(j)) {
                    rightSideGraph.put(j, new LongOpenHashSet(new long[] { i }));
                } else {
                    rightSideGraph.get(j).add(i);
                }
                edges.add(Pair.of((long) i, (long) j));
            }
        }
        leftSideGraph.put(i, nodeEdges);
    }

    // Create a bunch of leftReaders per node that'll read from the graph at random
    for (int i = 0; i < leftSize; i++) {
        for (int j = 0; j < numReadersPerNode; j++) {
            leftReaders.add(new BipartiteGraphReader(graph, new CountDownLatch(0), readersDoneLatch, i, true,
                    random.nextInt(maxWaitingTimeForThreads)));
        }
    }

    // Create a bunch of rightReaders per node that'll read from the graph at random
    for (int i = 0; i < rightSize; i++) {
        for (int j = 0; j < numReadersPerNode; j++) {
            rightReaders.add(new BipartiteGraphReader(graph, new CountDownLatch(0), readersDoneLatch, i, false,
                    random.nextInt(maxWaitingTimeForThreads)));
        }
    }

    // Create a single writer that will insert these edges in random order
    List<WriterInfo> writerInfo = Lists.newArrayListWithCapacity(edges.size());
    List<Pair<Long, Long>> edgesList = Lists.newArrayList(edges);
    Collections.shuffle(edgesList);
    CountDownLatch writerDoneLatch = new CountDownLatch(edgesList.size());
    for (Pair<Long, Long> edge : edgesList) {
        writerInfo.add(new WriterInfo(edge.getLeft(), edge.getRight(), new CountDownLatch(0), writerDoneLatch));
    }

    ExecutorService executor = Executors.newFixedThreadPool(totalNumReaders + 1); // single writer
    List<Callable<Integer>> allThreads = Lists.newArrayListWithCapacity(totalNumReaders + 1);
    // First, we add the writer
    allThreads.add(Executors.callable(new BipartiteGraphWriter(graph, writerInfo), 1));
    // then the readers
    for (int i = 0; i < numLeftReaders; i++) {
        allThreads.add(Executors.callable(leftReaders.get(i), 1));
    }
    for (int i = 0; i < numRightReaders; i++) {
        allThreads.add(Executors.callable(rightReaders.get(i), 1));
    }
    // these will execute in some non-deterministic order
    Collections.shuffle(allThreads, random);

    // Wait for all the processes to finish
    try {
        List<Future<Integer>> results = executor.invokeAll(allThreads, 10, TimeUnit.SECONDS);
        for (Future<Integer> result : results) {
            assertTrue(result.isDone());
            assertEquals(1, result.get().intValue());
        }
    } catch (InterruptedException e) {
        throw new RuntimeException("Execution for a thread was interrupted: ", e);
    } catch (ExecutionException e) {
        throw new RuntimeException("Execution issue in an executor thread: ", e);
    }

    // confirm that these worked as expected
    try {
        readersDoneLatch.await();
        writerDoneLatch.await();
    } catch (InterruptedException e) {
        throw new RuntimeException("Execution for a latch was interrupted: ", e);
    }

    // Check that all readers' read info is consistent with the graph
    // first check the left side
    for (int i = 0; i < numLeftReaders; i++) {
        LongSet expectedLeftEdges = leftSideGraph.get(leftReaders.get(i).queryNode);
        assertTrue(leftReaders.get(i).getQueryNodeDegree() <= expectedLeftEdges.size());
        if (leftReaders.get(i).getQueryNodeDegree() == 0) {
            assertNull(leftReaders.get(i).getQueryNodeEdges());
        } else {
            for (long edge : leftReaders.get(i).getQueryNodeEdges()) {
                assertTrue(expectedLeftEdges.contains(edge));
            }
        }
    }

    // then the right side
    for (int i = 0; i < numRightReaders; i++) {
        LongSet expectedRightEdges = rightSideGraph.get(rightReaders.get(i).queryNode);
        assertTrue(rightReaders.get(i).getQueryNodeDegree() <= expectedRightEdges.size());
        if (rightReaders.get(i).getQueryNodeDegree() == 0) {
            assertNull(rightReaders.get(i).getQueryNodeEdges());
        } else {
            for (long edge : rightReaders.get(i).getQueryNodeEdges()) {
                assertTrue(expectedRightEdges.contains(edge));
            }
        }
    }
}