Search in sources :

Example 91 with FutureTask

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

the class OptimizeImportsProcessor method prepareTask.

@Override
@NotNull
protected FutureTask<Boolean> prepareTask(@NotNull PsiFile file, boolean processChangedTextOnly) {
    if (DumbService.isDumb(file.getProject())) {
        return new FutureTask<>(EmptyRunnable.INSTANCE, true);
    }
    final Set<ImportOptimizer> optimizers = LanguageImportStatements.INSTANCE.forFile(file);
    final List<Runnable> runnables = new ArrayList<>();
    List<PsiFile> files = file.getViewProvider().getAllFiles();
    for (ImportOptimizer optimizer : optimizers) {
        for (PsiFile psiFile : files) {
            if (optimizer.supports(psiFile)) {
                runnables.add(optimizer.processFile(psiFile));
            }
        }
    }
    Runnable runnable = !runnables.isEmpty() ? () -> {
        CodeStyleManagerImpl.setSequentialProcessingAllowed(false);
        try {
            for (Runnable runnable1 : runnables) {
                runnable1.run();
                retrieveAndStoreNotificationInfo(runnable1);
            }
            putNotificationInfoIntoCollector();
        } finally {
            CodeStyleManagerImpl.setSequentialProcessingAllowed(true);
        }
    } : EmptyRunnable.getInstance();
    return new FutureTask<>(runnable, true);
}
Also used : FutureTask(java.util.concurrent.FutureTask) EmptyRunnable(com.intellij.openapi.util.EmptyRunnable) ArrayList(java.util.ArrayList) PsiFile(com.intellij.psi.PsiFile) ImportOptimizer(com.intellij.lang.ImportOptimizer) NotNull(org.jetbrains.annotations.NotNull)

Example 92 with FutureTask

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

the class AbstractLayoutCodeProcessor method runProcessFile.

private void runProcessFile(@NotNull final PsiFile file) {
    Document document = PsiDocumentManager.getInstance(myProject).getDocument(file);
    if (document == null) {
        return;
    }
    if (!FileDocumentManager.getInstance().requestWriting(document, myProject)) {
        Messages.showMessageDialog(myProject, PsiBundle.message("cannot.modify.a.read.only.file", file.getName()), CodeInsightBundle.message("error.dialog.readonly.file.title"), Messages.getErrorIcon());
        return;
    }
    final Ref<FutureTask<Boolean>> writeActionRunnable = new Ref<>();
    Runnable readAction = () -> {
        if (!checkFileWritable(file))
            return;
        try {
            FutureTask<Boolean> writeTask = preprocessFile(file, myProcessChangedTextOnly);
            writeActionRunnable.set(writeTask);
        } catch (IncorrectOperationException e) {
            LOG.error(e);
        }
    };
    Runnable writeAction = () -> {
        if (writeActionRunnable.isNull())
            return;
        FutureTask<Boolean> task = writeActionRunnable.get();
        task.run();
        try {
            task.get();
        } catch (CancellationException ignored) {
        } catch (ExecutionException e) {
            if (e.getCause() instanceof IndexNotReadyException) {
                throw (IndexNotReadyException) e.getCause();
            }
            LOG.error(e);
        } catch (Exception e) {
            LOG.error(e);
        }
    };
    runLayoutCodeProcess(readAction, writeAction);
}
Also used : Ref(com.intellij.openapi.util.Ref) FutureTask(java.util.concurrent.FutureTask) CancellationException(java.util.concurrent.CancellationException) IndexNotReadyException(com.intellij.openapi.project.IndexNotReadyException) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Document(com.intellij.openapi.editor.Document) ExecutionException(java.util.concurrent.ExecutionException) IncorrectOperationException(com.intellij.util.IncorrectOperationException) IndexNotReadyException(com.intellij.openapi.project.IndexNotReadyException) CancellationException(java.util.concurrent.CancellationException) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) FilesTooBigForDiffException(com.intellij.util.diff.FilesTooBigForDiffException) ExecutionException(java.util.concurrent.ExecutionException)

Example 93 with FutureTask

use of java.util.concurrent.FutureTask in project android-priority-jobqueue by yigit.

the class KeepAliveTest method testKeepAlive.

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void testKeepAlive(final DummyNetworkUtil networkUtil) throws Exception {
    int keepAlive = 3;
    final JobManager jobManager = createJobManager(new Configuration.Builder(RuntimeEnvironment.application).consumerKeepAlive(keepAlive).networkUtil(networkUtil).timer(mockTimer));
    //give it a little time to create first consumer
    final CountDownLatch jobDone = new CountDownLatch(1);
    jobManager.addCallback(new JobManagerCallbackAdapter() {

        @Override
        public void onDone(@NonNull Job job) {
            jobDone.countDown();
        }
    });
    jobManager.addJob(new DummyJob(new Params(0)));
    // Sync on job manager to ensure it handled add requests
    jobManager.count();
    MatcherAssert.assertThat("there should be 1 thread  actively waiting for jobs", jobManager.getActiveConsumerCount(), equalTo(1));
    MatcherAssert.assertThat(jobDone.await(1, TimeUnit.MINUTES), CoreMatchers.is(true));
    // Sync on job manager to ensure it handled add requests
    jobManager.count();
    mockTimer.incrementNs((long) (JobManager.NETWORK_CHECK_INTERVAL + TimeUnit.SECONDS.toNanos(keepAlive) + 1));
    FutureTask<Void> waitForConsumersFuture = new FutureTask<>(new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            jobManager.waitUntilConsumersAreFinished();
            return null;
        }
    });
    new Thread(waitForConsumersFuture).start();
    waitForConsumersFuture.get(keepAlive * 10, TimeUnit.SECONDS);
    jobManager.waitUntilConsumersAreFinished();
    MatcherAssert.assertThat("after keep alive timeout, there should NOT be any threads waiting", jobManager.getActiveConsumerCount(), equalTo(0));
    //disable network and add a network bound job
    networkUtil.setNetworkStatus(NetworkUtil.DISCONNECTED);
    final DummyJob dj1 = new DummyJob(new Params(0).requireNetwork());
    jobManager.addJob(dj1);
    // sync add job request
    jobManager.count();
    mockTimer.incrementNs(JobManager.NETWORK_CHECK_INTERVAL + TimeUnit.SECONDS.toNanos(keepAlive) * 2);
    waitUntilAJobIsDone(jobManager, new WaitUntilCallback() {

        @Override
        public void run() {
            networkUtil.setNetworkStatus(NetworkUtil.METERED);
        }

        @Override
        public void assertJob(Job job) {
            Assert.assertThat("it should be dj1", job, is((Job) dj1));
        }
    });
    MatcherAssert.assertThat("when network is recovered, job should be handled", jobManager.count(), equalTo(0));
}
Also used : JobManagerCallbackAdapter(com.birbit.android.jobqueue.callback.JobManagerCallbackAdapter) Params(com.birbit.android.jobqueue.Params) JobManager(com.birbit.android.jobqueue.JobManager) CountDownLatch(java.util.concurrent.CountDownLatch) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) FutureTask(java.util.concurrent.FutureTask) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) Job(com.birbit.android.jobqueue.Job) TargetApi(android.annotation.TargetApi)

Example 94 with FutureTask

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

the class VcsRepositoryManagerTest method testRepositoryInfoReadingWhileModifying.

public void testRepositoryInfoReadingWhileModifying() throws Exception {
    final VirtualFile repositoryFile = createExternalRepository();
    assertNotNull(myGlobalRepositoryManager.getRepositoryForRoot(repositoryFile));
    FutureTask<Repository> readExistingRepo = new FutureTask<>(new Callable<Repository>() {

        @Override
        public Repository call() throws Exception {
            return myGlobalRepositoryManager.getRepositoryForRoot(repositoryFile);
        }
    });
    FutureTask<Boolean> modifyRepositoryMapping = new FutureTask<>(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            myProjectLevelVcsManager.setDirectoryMappings(VcsUtil.addMapping(myProjectLevelVcsManager.getDirectoryMappings(), myProjectRoot.getPath(), myVcs.getName()));
            return !myGlobalRepositoryManager.getRepositories().isEmpty();
        }
    });
    Thread modify = new Thread(modifyRepositoryMapping, "vcs modify");
    modify.start();
    //wait until modification starts
    assertTrue(LOCK_ERROR_TEXT, READY_TO_READ.await(1, TimeUnit.SECONDS));
    Thread read = new Thread(readExistingRepo, "vcs read");
    read.start();
    assertNotNull(readExistingRepo.get(1, TimeUnit.SECONDS));
    CONTINUE_MODIFY.countDown();
    assertTrue(modifyRepositoryMapping.get(1, TimeUnit.SECONDS));
    read.join();
    modify.join();
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Repository(com.intellij.dvcs.repo.Repository) FutureTask(java.util.concurrent.FutureTask)

Example 95 with FutureTask

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

the class MtpManagerTest method testCancelEvent.

public void testCancelEvent() throws Exception {
    final CancellationSignal signal = new CancellationSignal();
    final FutureTask<Boolean> future = new FutureTask<Boolean>(new Callable<Boolean>() {

        @Override
        public Boolean call() throws IOException {
            try {
                while (true) {
                    mManager.readEvent(mUsbDevice.getDeviceId(), signal);
                }
            } catch (OperationCanceledException exception) {
                return true;
            }
        }
    });
    final Thread thread = new Thread(future);
    thread.start();
    SystemClock.sleep(TIMEOUT_MS);
    signal.cancel();
    assertTrue(future.get(TIMEOUT_MS, TimeUnit.MILLISECONDS));
}
Also used : FutureTask(java.util.concurrent.FutureTask) OperationCanceledException(android.os.OperationCanceledException) IOException(java.io.IOException) CancellationSignal(android.os.CancellationSignal)

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