Search in sources :

Example 86 with FutureTask

use of java.util.concurrent.FutureTask in project neo4j by neo4j.

the class ClusterTransactionIT method givenClusterWhenShutdownMasterThenCannotStartTransactionOnSlave.

@Test
public void givenClusterWhenShutdownMasterThenCannotStartTransactionOnSlave() throws Throwable {
    final HighlyAvailableGraphDatabase master = cluster.getMaster();
    final HighlyAvailableGraphDatabase slave = cluster.getAnySlave();
    final long nodeId;
    try (Transaction tx = master.beginTx()) {
        nodeId = master.createNode().getId();
        tx.success();
    }
    cluster.sync();
    // When
    final FutureTask<Boolean> result = new FutureTask<>(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            try (Transaction tx = slave.beginTx()) {
                tx.acquireWriteLock(slave.getNodeById(nodeId));
            } catch (Exception e) {
                return contains(e, TransactionFailureException.class);
            }
            // Fail otherwise
            return false;
        }
    });
    master.getDependencyResolver().resolveDependency(LifeSupport.class).addLifecycleListener(new LifecycleListener() {

        @Override
        public void notifyStatusChanged(Object instance, LifecycleStatus from, LifecycleStatus to) {
            if (instance.getClass().getName().contains("DatabaseAvailability") && to == LifecycleStatus.STOPPED) {
                result.run();
            }
        }
    });
    master.shutdown();
    // Then
    assertThat(result.get(), equalTo(true));
}
Also used : LifecycleListener(org.neo4j.kernel.lifecycle.LifecycleListener) TransactionFailureException(org.neo4j.kernel.api.exceptions.TransactionFailureException) Transaction(org.neo4j.graphdb.Transaction) FutureTask(java.util.concurrent.FutureTask) HighlyAvailableGraphDatabase(org.neo4j.kernel.ha.HighlyAvailableGraphDatabase) LifecycleStatus(org.neo4j.kernel.lifecycle.LifecycleStatus) LifeSupport(org.neo4j.kernel.lifecycle.LifeSupport) Test(org.junit.Test)

Example 87 with FutureTask

use of java.util.concurrent.FutureTask in project double-espresso by JakeWharton.

the class QueueInterrogator method initializeQueue.

private void initializeQueue() {
    if (interrogatedLooper == Looper.myLooper()) {
        interrogatedQueue = Looper.myQueue();
    } else {
        Handler oneShotHandler = new Handler(interrogatedLooper);
        FutureTask<MessageQueue> queueCapture = new FutureTask<MessageQueue>(new Callable<MessageQueue>() {

            @Override
            public MessageQueue call() {
                return Looper.myQueue();
            }
        });
        oneShotHandler.postAtFrontOfQueue(queueCapture);
        try {
            interrogatedQueue = queueCapture.get();
        } catch (ExecutionException ee) {
            throw propagate(ee.getCause());
        } catch (InterruptedException ie) {
            throw propagate(ie);
        }
    }
}
Also used : FutureTask(java.util.concurrent.FutureTask) MessageQueue(android.os.MessageQueue) Handler(android.os.Handler) ExecutionException(java.util.concurrent.ExecutionException)

Example 88 with FutureTask

use of java.util.concurrent.FutureTask in project cogcomp-nlp by CogComp.

the class CrossValidationHelper method tryParamParallel.

private PerformanceMeasure tryParamParallel(DatasetType train, LearnerParameters param) throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool(nFolds);
    final AbstractInferenceSolver[][] foldWiseInference = splitInference(inference, nFolds);
    List<FutureTask<PerformanceMeasure>> tasks = new ArrayList<>();
    for (int foldId = 0; foldId < nFolds; foldId++) {
        Pair<DatasetType, DatasetType> foldData = foldSplitter.getFoldData(train, foldId);
        FutureTask<PerformanceMeasure> future = createTask(foldData.getFirst(), foldData.getSecond(), param, foldWiseInference[foldId], foldId);
        tasks.add(future);
        executor.execute(future);
    }
    executor.shutdown();
    int foldId = 0;
    List<PerformanceMeasure> perf = new ArrayList<>();
    for (FutureTask<PerformanceMeasure> task : tasks) {
        log.info("Waiting for results of fold {}", foldId);
        PerformanceMeasure measure = task.get();
        log.info("Fold {} complete.", foldId);
        perf.add(measure);
        foldId++;
    }
    return averager.average(perf);
}
Also used : FutureTask(java.util.concurrent.FutureTask) ExecutorService(java.util.concurrent.ExecutorService) ArrayList(java.util.ArrayList)

Example 89 with FutureTask

use of java.util.concurrent.FutureTask in project android_frameworks_base by DirtyUnicorns.

the class MffTestCase method setUp.

@Override
protected void setUp() throws Exception {
    super.setUp();
    // MffContext needs to be created on a separate thread to allow MFF to post Runnable's.
    mMffContextHandlerThread = new HandlerThread("MffContextThread");
    mMffContextHandlerThread.start();
    Handler handler = new Handler(mMffContextHandlerThread.getLooper());
    FutureTask<MffContext> task = new FutureTask<MffContext>(new Callable<MffContext>() {

        @Override
        public MffContext call() throws Exception {
            MffContext.Config config = new MffContext.Config();
            config.requireCamera = false;
            config.requireOpenGL = false;
            config.forceNoGL = true;
            return new MffContext(getContext(), config);
        }
    });
    handler.post(task);
    // Wait for the context to be created on the handler thread.
    mMffContext = task.get();
}
Also used : HandlerThread(android.os.HandlerThread) FutureTask(java.util.concurrent.FutureTask) Handler(android.os.Handler)

Example 90 with FutureTask

use of java.util.concurrent.FutureTask in project intellij-community by JetBrains.

the class ReformatCodeProcessor method prepareTask.

@Override
@NotNull
protected FutureTask<Boolean> prepareTask(@NotNull final PsiFile file, final boolean processChangedTextOnly) throws IncorrectOperationException {
    return new FutureTask<>(() -> {
        FormattingProgressTask.FORMATTING_CANCELLED_FLAG.set(false);
        try {
            CharSequence before = null;
            Document document = PsiDocumentManager.getInstance(myProject).getDocument(file);
            if (getInfoCollector() != null) {
                LOG.assertTrue(document != null);
                before = document.getImmutableCharSequence();
            }
            CaretVisualPositionKeeper caretPositionKeeper = new CaretVisualPositionKeeper(document);
            if (processChangedTextOnly) {
                ChangedRangesInfo info = FormatChangedTextUtil.getInstance().getChangedRangesInfo(file);
                if (info != null) {
                    CodeStyleManager.getInstance(myProject).reformatTextWithContext(file, info);
                }
            } else {
                Collection<TextRange> ranges = getRangesToFormat(file);
                CodeStyleManager.getInstance(myProject).reformatText(file, ranges);
            }
            caretPositionKeeper.restoreOriginalLocation();
            if (before != null) {
                prepareUserNotificationMessage(document, before);
            }
            return !FormattingProgressTask.FORMATTING_CANCELLED_FLAG.get();
        } catch (FilesTooBigForDiffException e) {
            handleFileTooBigException(LOG, e, file);
            return false;
        } catch (IncorrectOperationException e) {
            LOG.error(e);
            return false;
        } finally {
            myRanges.clear();
        }
    });
}
Also used : FilesTooBigForDiffException(com.intellij.util.diff.FilesTooBigForDiffException) FutureTask(java.util.concurrent.FutureTask) TextRange(com.intellij.openapi.util.TextRange) IncorrectOperationException(com.intellij.util.IncorrectOperationException) ChangedRangesInfo(com.intellij.psi.codeStyle.ChangedRangesInfo) Document(com.intellij.openapi.editor.Document) CaretVisualPositionKeeper(com.intellij.openapi.editor.ex.util.CaretVisualPositionKeeper) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

FutureTask (java.util.concurrent.FutureTask)126 ExecutionException (java.util.concurrent.ExecutionException)44 Test (org.junit.Test)32 IOException (java.io.IOException)28 ExecutorService (java.util.concurrent.ExecutorService)23 Callable (java.util.concurrent.Callable)22 CountDownLatch (java.util.concurrent.CountDownLatch)20 TimeoutException (java.util.concurrent.TimeoutException)14 Handler (android.os.Handler)12 ArrayList (java.util.ArrayList)12 CancellationException (java.util.concurrent.CancellationException)10 InvocationTargetException (java.lang.reflect.InvocationTargetException)9 Future (java.util.concurrent.Future)8 AccessibleObject (java.lang.reflect.AccessibleObject)6 List (java.util.List)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 FileNotFoundException (java.io.FileNotFoundException)5 InputStream (java.io.InputStream)5 Iterator (java.util.Iterator)5 CancellationSignal (android.os.CancellationSignal)4