Search in sources :

Example 26 with CancellationException

use of java.util.concurrent.CancellationException in project elasticsearch-jdbc by jprante.

the class JDBCImporter method run.

@Override
public void run() {
    try {
        prepare();
        futures = schedule(settings);
        if (!futures.isEmpty()) {
            logger.debug("waiting for {} futures...", futures.size());
            for (Future future : futures) {
                try {
                    Object o = future.get();
                    logger.debug("got future {}", o);
                } catch (CancellationException e) {
                    logger.warn("schedule canceled");
                } catch (InterruptedException e) {
                    logger.error(e.getMessage());
                } catch (ExecutionException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            logger.debug("futures complete");
        } else {
            execute();
        }
    } catch (Throwable e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            if (context != null) {
                context.shutdown();
                context = null;
            }
        } catch (Throwable e) {
            logger.warn(e.getMessage(), e);
        }
    }
}
Also used : CancellationException(java.util.concurrent.CancellationException) Future(java.util.concurrent.Future) ExecutionException(java.util.concurrent.ExecutionException)

Example 27 with CancellationException

use of java.util.concurrent.CancellationException in project PayFile by mikehearn.

the class Controller method download.

public void download(ActionEvent event) throws Exception {
    File destination = null;
    try {
        final PayFileClient.File downloadingFile = checkNotNull(selectedFile.get());
        if (downloadingFile.getPrice() > getBalance().longValue())
            throw new InsufficientMoneyException(BigInteger.valueOf(downloadingFile.getPrice() - getBalance().longValue()));
        // Ask the user where to put it.
        DirectoryChooser chooser = new DirectoryChooser();
        chooser.setTitle("Select download directory");
        File directory = chooser.showDialog(Main.instance.mainWindow);
        if (directory == null)
            return;
        destination = new File(directory, downloadingFile.getFileName());
        FileOutputStream fileStream = new FileOutputStream(destination);
        final long startTime = System.currentTimeMillis();
        cancelBtn.setVisible(true);
        progressBarLabel.setText("Downloading " + downloadingFile.getFileName());
        // Make the UI update whilst the download is in progress: progress bar and balance label.
        ProgressOutputStream stream = new ProgressOutputStream(fileStream, downloadingFile.getSize());
        progressBar.progressProperty().bind(stream.progressProperty());
        Main.client.setOnPaymentMade((amt) -> Platform.runLater(this::refreshBalanceLabel));
        // Swap in the progress bar with an animation.
        animateSwap();
        // ... and start the download.
        Settings.setLastPaidServer(Main.serverAddress);
        downloadFuture = Main.client.downloadFile(downloadingFile, stream);
        final File fDestination = destination;
        // When we're done ...
        downloadFuture.handleAsync((ok, exception) -> {
            // ... swap widgets back out again
            animateSwap();
            if (exception != null) {
                if (!(exception instanceof CancellationException))
                    crashAlert(exception);
            } else {
                // Otherwise inform the user we're finished and let them open the file.
                int secondsTaken = (int) (System.currentTimeMillis() - startTime) / 1000;
                runAlert((stage, controller) -> controller.withOpenFile(stage, downloadingFile, fDestination, secondsTaken));
            }
            return null;
        }, Platform::runLater);
    } catch (InsufficientMoneyException e) {
        if (destination != null)
            destination.delete();
        final String price = Utils.bitcoinValueToFriendlyString(BigInteger.valueOf(selectedFile.get().getPrice()));
        final String missing = String.valueOf(e.missing);
        informationalAlert("Insufficient funds", "This file costs %s BTC but you can't afford that. You need %s satoshis to complete the transaction.", price, missing);
    }
}
Also used : PayFileClient(net.plan99.payfile.client.PayFileClient) Platform(javafx.application.Platform) CancellationException(java.util.concurrent.CancellationException) FileOutputStream(java.io.FileOutputStream) File(java.io.File) DirectoryChooser(javafx.stage.DirectoryChooser)

Example 28 with CancellationException

use of java.util.concurrent.CancellationException in project bagheera by mozilla-metrics.

the class KafkaConsumer method poll.

@Override
public void poll() {
    final CountDownLatch latch = new CountDownLatch(streams.size());
    for (final KafkaStream<Message> stream : streams) {
        workers.add(executor.submit(new Callable<Void>() {

            @Override
            public Void call() {
                try {
                    for (MessageAndMetadata<Message> mam : stream) {
                        BagheeraMessage bmsg = BagheeraMessage.parseFrom(ByteString.copyFrom(mam.message().payload()));
                        // get the sink for this message's namespace 
                        // (typically only one sink unless a regex pattern was used to listen to multiple topics)
                        KeyValueSink sink = sinkFactory.getSink(bmsg.getNamespace());
                        if (sink == null) {
                            LOG.error("Could not obtain sink for namespace: " + bmsg.getNamespace());
                            break;
                        }
                        if (bmsg.getOperation() == Operation.CREATE_UPDATE && bmsg.hasId() && bmsg.hasPayload()) {
                            if (validationPipeline == null || validationPipeline.isValid(bmsg.getPayload().toByteArray())) {
                                if (bmsg.hasTimestamp()) {
                                    sink.store(bmsg.getId(), bmsg.getPayload().toByteArray(), bmsg.getTimestamp());
                                } else {
                                    sink.store(bmsg.getId(), bmsg.getPayload().toByteArray());
                                }
                            } else {
                                invalidMessageMeter.mark();
                                // TODO: sample out an example payload
                                LOG.warn("Invalid payload for namespace: " + bmsg.getNamespace());
                            }
                        } else if (bmsg.getOperation() == Operation.DELETE && bmsg.hasId()) {
                            sink.delete(bmsg.getId());
                        }
                        consumed.mark();
                    }
                } catch (InvalidProtocolBufferException e) {
                    LOG.error("Invalid protocol buffer in data stream", e);
                } catch (UnsupportedEncodingException e) {
                    LOG.error("Message ID was not in UTF-8 encoding", e);
                } catch (IOException e) {
                    LOG.error("IO error while storing to data sink", e);
                } finally {
                    latch.countDown();
                }
                return null;
            }
        }));
    }
    // run indefinitely unless we detect that a thread exited
    try {
        while (true) {
            latch.await(10, TimeUnit.SECONDS);
            if (latch.getCount() != streams.size()) {
                // we have a dead thread and should exit
                break;
            }
        }
    } catch (InterruptedException e) {
        LOG.info("Interrupted during polling", e);
    }
    // Spit out errors if there were any
    for (Future<Void> worker : workers) {
        try {
            if (worker.isDone() && !worker.isCancelled()) {
                worker.get(1, TimeUnit.SECONDS);
            }
        } catch (InterruptedException e) {
            LOG.error("Thread was interrupted:", e);
        } catch (ExecutionException e) {
            LOG.error("Exception occured in thread:", e);
        } catch (TimeoutException e) {
            LOG.error("Timed out waiting for thread result:", e);
        } catch (CancellationException e) {
            LOG.error("Thread has been canceled: ", e);
        }
    }
}
Also used : BagheeraMessage(com.mozilla.bagheera.BagheeraProto.BagheeraMessage) Message(kafka.message.Message) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Callable(java.util.concurrent.Callable) KeyValueSink(com.mozilla.bagheera.sink.KeyValueSink) CancellationException(java.util.concurrent.CancellationException) BagheeraMessage(com.mozilla.bagheera.BagheeraProto.BagheeraMessage) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 29 with CancellationException

use of java.util.concurrent.CancellationException in project quasar by puniverse.

the class Val method get.

/**
     * Returns the delayed value, blocking until it has been set, but no longer than the given timeout.
     *
     * @param timeout The maximum duration to block waiting for the value to be set.
     * @param unit    The time unit of the timeout value.
     * @return the value
     * @throws TimeoutException     if the timeout expires before the value is set.
     * @throws InterruptedException
     */
@Override
@Suspendable
public V get(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException {
    try {
        final SimpleConditionSynchronizer s = sync;
        if (s != null) {
            Object token = s.register();
            try {
                final long start = System.nanoTime();
                long left = unit.toNanos(timeout);
                final long deadline = start + left;
                for (int i = 0; sync != null; i++) {
                    s.awaitNanos(i, left);
                    if (sync == null)
                        break;
                    left = deadline - System.nanoTime();
                    if (left <= 0)
                        throw new TimeoutException();
                }
            } finally {
                s.unregister(token);
            }
        }
        if (t != null)
            throw t instanceof CancellationException ? (CancellationException) t : new RuntimeExecutionException(t);
        return value;
    } catch (SuspendExecution e) {
        throw new AssertionError(e);
    }
}
Also used : SimpleConditionSynchronizer(co.paralleluniverse.strands.SimpleConditionSynchronizer) SuspendExecution(co.paralleluniverse.fibers.SuspendExecution) CancellationException(java.util.concurrent.CancellationException) TimeoutException(java.util.concurrent.TimeoutException) RuntimeExecutionException(co.paralleluniverse.fibers.RuntimeExecutionException) Suspendable(co.paralleluniverse.fibers.Suspendable)

Example 30 with CancellationException

use of java.util.concurrent.CancellationException in project quasar by puniverse.

the class FiberTest method testCancel2.

@Test
public void testCancel2() throws Exception {
    final AtomicBoolean started = new AtomicBoolean();
    final AtomicBoolean terminated = new AtomicBoolean();
    Fiber fiber = new Fiber(scheduler, new SuspendableRunnable() {

        @Override
        public void run() throws SuspendExecution {
            started.set(true);
            try {
                Fiber.sleep(100);
                fail("InterruptedException not thrown");
            } catch (InterruptedException e) {
            }
            terminated.set(true);
        }
    });
    fiber.cancel(true);
    fiber.start();
    Thread.sleep(20);
    try {
        fiber.join(5, TimeUnit.MILLISECONDS);
        fail();
    } catch (CancellationException e) {
    }
    assertThat(started.get(), is(false));
    assertThat(terminated.get(), is(false));
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SuspendableRunnable(co.paralleluniverse.strands.SuspendableRunnable) CancellationException(java.util.concurrent.CancellationException) Test(org.junit.Test)

Aggregations

CancellationException (java.util.concurrent.CancellationException)178 ExecutionException (java.util.concurrent.ExecutionException)84 TimeoutException (java.util.concurrent.TimeoutException)49 Test (org.junit.Test)28 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)25 IOException (java.io.IOException)24 CountDownLatch (java.util.concurrent.CountDownLatch)22 Future (java.util.concurrent.Future)22 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)16 Callable (java.util.concurrent.Callable)15 ArrayList (java.util.ArrayList)14 ExecutorService (java.util.concurrent.ExecutorService)13 File (java.io.File)11 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 InvocationTargetException (java.lang.reflect.InvocationTargetException)7 FutureTask (java.util.concurrent.FutureTask)7 Handler (android.os.Handler)6 GwtIncompatible (com.google.common.annotations.GwtIncompatible)6 AccessibleObject (java.lang.reflect.AccessibleObject)6 List (java.util.List)6