Example usage for java.util.concurrent Executor execute

List of usage examples for java.util.concurrent Executor execute

Introduction

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

Prototype

void execute(Runnable command);

Source Link

Document

Executes the given command at some time in the future.

Usage

From source file:com.mirth.connect.client.ui.components.ChannelTableTransferHandler.java

@Override
public boolean importData(TransferSupport support) {
    if (canImport(support)) {
        try {/*  w  w  w  .  j  a  va2s  .c  om*/
            if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                List<File> fileList = (List<File>) support.getTransferable()
                        .getTransferData(DataFlavor.javaFileListFlavor);
                final boolean showAlerts = (fileList.size() == 1);

                // Submit each import task to a single-threaded executor so they always import one at a time.
                Executor executor = Executors.newSingleThreadExecutor();

                for (final File file : fileList) {
                    if (FilenameUtils.isExtension(file.getName(), "xml")) {
                        executor.execute(new Runnable() {
                            @Override
                            public void run() {
                                importFile(file, showAlerts);
                            }
                        });
                    }
                }

                return true;
            } else if (support.isDataFlavorSupported(ChannelTableTransferable.CHANNEL_DATA_FLAVOR)) {
                List<Object> list = (List<Object>) support.getTransferable()
                        .getTransferData(ChannelTableTransferable.CHANNEL_DATA_FLAVOR);

                List<Channel> channels = new ArrayList<Channel>();
                for (Object obj : list) {
                    if (obj instanceof Channel) {
                        channels.add((Channel) obj);
                    } else {
                        return false;
                    }
                }

                if (support.getDropLocation() instanceof JTable.DropLocation) {
                    return moveChannels(channels, ((JTable.DropLocation) support.getDropLocation()).getRow());
                }
            }
        } catch (Exception e) {
            // Let it return false
        }
    }

    return false;
}

From source file:io.druid.server.initialization.JettyTest.java

@Test
@Ignore // this test will deadlock if it hits an issue, so ignored by default
public void testTimeouts() throws Exception {
    // test for request timeouts properly not locking up all threads
    final Executor executor = Executors.newFixedThreadPool(100);
    final AtomicLong count = new AtomicLong(0);
    final CountDownLatch latch = new CountDownLatch(1000);
    for (int i = 0; i < 10000; i++) {
        executor.execute(new Runnable() {
            @Override//from  ww w . jav  a  2s  .  c o  m
            public void run() {
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        long startTime = System.currentTimeMillis();
                        long startTime2 = 0;
                        try {
                            ListenableFuture<StatusResponseHolder> go = client.go(
                                    new Request(HttpMethod.GET,
                                            new URL("http://localhost:" + port + "/slow/hello")),
                                    new StatusResponseHandler(Charset.defaultCharset()));
                            startTime2 = System.currentTimeMillis();
                            go.get();
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            System.out.println("Response time client" + (System.currentTimeMillis() - startTime)
                                    + "time taken for getting future"
                                    + (System.currentTimeMillis() - startTime2) + "Counter "
                                    + count.incrementAndGet());
                            latch.countDown();

                        }
                    }
                });
            }
        });
    }

    latch.await();
}

From source file:org.commonjava.indy.subsys.git.GitManagerConcurrentTest.java

@BMRules(rules = {
        @BMRule(name = "init rendezvous", targetClass = "GitManager", targetMethod = "<init>", targetLocation = "ENTRY", action = "createRendezvous($0, 2, true)"),
        @BMRule(name = "addAndCommitPaths call", targetClass = "GitManager", targetMethod = "addAndCommitPaths(ChangeSummary,Collection)", targetLocation = "ENTRY", action = "rendezvous($0); debug(Thread.currentThread().getName() + \": thread proceeding.\")"), })
@Test/*from   w  w  w.j  a va  2 s .  c  o  m*/
public void concurrentAddToRepo() throws Exception {

    final int threshold = 2;
    final Executor pool = Executors.newFixedThreadPool(threshold);
    CountDownLatch latch = new CountDownLatch(threshold);

    for (int i = 0; i < threshold; i++) {
        final int j = i;
        pool.execute(() -> {
            try {
                final File f = new File(cloneDir, String.format("test%s.txt", j));
                FileUtils.write(f, String.format("This is a test %s", j));

                final String user = "test" + j;
                final String log = "test commit " + j;
                git.addFiles(new ChangeSummary(user, log), f);
                git.commit();
            } catch (Exception e) {
                e.printStackTrace();
                failed = true;
            } finally {
                latch.countDown();
            }
        });
    }

    latch.await();
    if (failed) {
        fail();
    }

}

From source file:org.commonjava.indy.subsys.git.GitManagerConcurrentTest.java

@BMRules(rules = {
        @BMRule(name = "init rendezvous", targetClass = "GitManager", targetMethod = "<init>", targetLocation = "ENTRY", action = "createRendezvous($0, 2, true)"),
        @BMRule(name = "deleteAndCommitPaths call", targetClass = "GitManager", targetMethod = "deleteAndCommitPaths(ChangeSummary,Collection)", targetLocation = "ENTRY", action = "rendezvous($0); debug(Thread.currentThread().getName() + \": thread proceeding.\")"), })
@Test//from  w  w w.  jav a2  s. c  o  m
public void concurrentDeleteFromRepo() throws Exception {
    final int threshold = 2;
    for (int i = 0; i < threshold; i++) {
        try {
            final File f = new File(cloneDir, String.format("test%s.txt", i));
            FileUtils.write(f, String.format("This is a test %s", i));

            final String user = "test" + i;
            final String log = "test commit " + i;
            git.addFiles(new ChangeSummary(user, log), f);
            git.commit();
        } catch (Exception e) {
            e.printStackTrace();
            failed = true;
        }
    }

    final Executor pool = Executors.newFixedThreadPool(threshold);
    CountDownLatch latch = new CountDownLatch(threshold);

    for (int i = 0; i < threshold; i++) {
        final int j = i;
        pool.execute(() -> {
            try {
                final File f = new File(cloneDir, String.format("test%s.txt", j));

                final String user = "test" + j;
                final String log = "delete test" + j + ".txt";
                git.delete(new ChangeSummary(user, log), f);
                git.commit();
            } catch (Exception e) {
                e.printStackTrace();
                failed = true;
            } finally {
                latch.countDown();
            }
        });
    }

    latch.await();
    if (failed) {
        fail();
    }

}

From source file:org.alfresco.repo.management.SafeApplicationEventMulticaster.java

@SuppressWarnings("unchecked")
protected void multicastEventInternal(final ApplicationEvent event) {
    for (final ApplicationListener listener : getApplicationListeners(event)) {
        Executor executor = getTaskExecutor();
        if (executor != null) {
            executor.execute(new Runnable() {
                public void run() {
                    listener.onApplicationEvent(event);
                }//from  w w  w  . j  a  v a  2s  .c  o m
            });
        } else {
            listener.onApplicationEvent(event);
        }
    }
}

From source file:org.commonjava.indy.filer.ispn.fileio.StorageFileIO.java

@Override
public void process(KeyFilter<? super String> filter, CacheLoaderTask<String, byte[]> task, Executor executor,
        boolean fetchValue, boolean fetchMetadata) {
    Path root = Paths.get(storageRoot);
    walkFiles((path -> {//w  ww . ja va2s  . com
        if (filter.accept(path.relativize(root).toString())) {
            executor.execute(() -> {
                if (Thread.currentThread().isInterrupted()) {
                    Logger logger = LoggerFactory.getLogger(getClass());
                    logger.debug("The cache-loader process thread is interrupted at the start. Bailing out.");
                    return;
                }

                try (ObjectInputStream in = new ObjectInputStream(
                        new GZIPInputStream(new FileInputStream(path.toFile())))) {
                    StorageFileEntry entry = new StorageFileEntry();
                    entry.load(in, fetchMetadata, fetchValue);

                    StorageFileTaskContext ctx = new StorageFileTaskContext();
                    task.processEntry(entry, ctx);
                } catch (ClassNotFoundException | IOException e) {
                    Logger logger = LoggerFactory.getLogger(getClass());
                    logger.error("Cannot read file: " + path, e);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    Logger logger = LoggerFactory.getLogger(getClass());
                    logger.debug("cache-loader process method interrupted on: " + path, e);
                }
            });
        }
    }));
}

From source file:com.tanmay.blip.networking.XKCDDownloader.java

private void downloadAllMissingTranscripts() {
    final Gson gson = new Gson();
    final DatabaseManager databaseManager = new DatabaseManager(this);
    List<Integer> nums = databaseManager.getAllMissingTranscripts();

    final CountDownLatch latch = new CountDownLatch(nums.size());
    final Executor executor = Executors.newFixedThreadPool(nums.size() / 2);
    for (int i : nums) {
        final int index = i;
        executor.execute(new Runnable() {
            @Override//from w  ww  .j a  v a  2  s .c o m
            public void run() {
                try {
                    String url = String.format(COMICS_URL, index);
                    Request request = new Request.Builder().url(url).build();
                    Response response = BlipApplication.getInstance().client.newCall(request).execute();
                    if (!response.isSuccessful())
                        throw new IOException();
                    String responseBody = response.body().string();
                    Comic comic = null;
                    try {
                        comic = gson.fromJson(responseBody, Comic.class);
                    } catch (JsonSyntaxException e) {
                        Crashlytics.log(1, "XKCDDownloader", e.getMessage() + " POS:" + index);
                    }
                    if (comic != null) {
                        databaseManager.updateComic(comic);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    LocalBroadcastManager.getInstance(XKCDDownloader.this)
                            .sendBroadcast(new Intent(DOWNLOAD_FAIL));
                } finally {
                    latch.countDown();
                }
            }
        });
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        LocalBroadcastManager.getInstance(XKCDDownloader.this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
    }
    SharedPrefs.getInstance().setLastTranscriptCheckTime(System.currentTimeMillis());
    LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_SUCCESS));

}

From source file:org.onlab.netty.NettyMessaging.java

@Override
public void registerHandler(String type, Consumer<byte[]> handler, Executor executor) {
    handlers.put(type, message -> executor.execute(() -> handler.accept(message.payload())));
}

From source file:org.onlab.netty.NettyMessaging.java

@Override
public void registerHandler(String type, Function<byte[], byte[]> handler, Executor executor) {
    handlers.put(type, message -> executor.execute(() -> {
        byte[] responsePayload = handler.apply(message.payload());
        if (responsePayload != null) {
            InternalMessage response = new InternalMessage(message.id(), localEp, REPLY_MESSAGE_TYPE,
                    responsePayload);//from  w  w w .  ja va 2 s .co m
            sendAsync(message.sender(), response).whenComplete((result, error) -> {
                if (error != null) {
                    log.debug("Failed to respond", error);
                }
            });
        }
    }));
}

From source file:com.tanmay.blip.networking.XKCDDownloader.java

private void downloadAll() {
    final Gson gson = new Gson();
    final DatabaseManager databaseManager = new DatabaseManager(this);
    Request request = new Request.Builder().url(LATEST_URL).build();
    try {/*from   ww  w  .j  a v a  2 s  .c om*/
        final Response response = BlipApplication.getInstance().client.newCall(request).execute();
        if (!response.isSuccessful())
            throw new IOException();
        Comic comic = gson.fromJson(response.body().string(), Comic.class);

        final int num = comic.getNum();
        final CountDownLatch latch = new CountDownLatch(num);
        final Executor executor = Executors.newFixedThreadPool(10);

        for (int i = 1; i <= num; i++) {
            final int index = i;
            executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        if (index != 404) {
                            String url = String.format(COMICS_URL, index);
                            Request newReq = new Request.Builder().url(url).build();
                            Response newResp = BlipApplication.getInstance().client.newCall(newReq).execute();
                            if (!newResp.isSuccessful())
                                throw new IOException();
                            String resp = newResp.body().string();
                            Comic comic1 = null;
                            try {
                                comic1 = gson.fromJson(resp, Comic.class);
                            } catch (JsonSyntaxException e) {
                                Crashlytics.log(1, "XKCDDownloader", e.getMessage() + " POS:" + index);
                            }
                            if (comic1 != null) {
                                databaseManager.addComic(comic1);
                                double progress = ((double) databaseManager.getCount() / num) * 100;
                                Intent intent = new Intent(DOWNLOAD_PROGRESS);
                                intent.putExtra(PROGRESS, progress);
                                intent.putExtra(TITLE, comic1.getTitle());
                                LocalBroadcastManager.getInstance(XKCDDownloader.this).sendBroadcast(intent);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        LocalBroadcastManager.getInstance(XKCDDownloader.this)
                                .sendBroadcast(new Intent(DOWNLOAD_FAIL));
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new IOException(e);
        }

        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_SUCCESS));
    } catch (IOException e) {
        e.printStackTrace();
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
    }
}