Example usage for java.util.concurrent FutureTask FutureTask

List of usage examples for java.util.concurrent FutureTask FutureTask

Introduction

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

Prototype

public FutureTask(Callable<V> callable) 

Source Link

Document

Creates a FutureTask that will, upon running, execute the given Callable .

Usage

From source file:co.pugo.convert.ConvertServlet.java

/**
 * download imageData and encode it base64
 * @param imageLinks set of image links extracted with extractImageLinks()
 * @return map, key = imageLink, value = base64 encoded image
 *//* w w  w  .j av  a2  s  .c o  m*/
private HashMap<String, String> downloadImageData(Set<String> imageLinks) {
    HashMap<String, String> imageData = new HashMap<>();
    ExecutorService service = Executors.newCachedThreadPool();
    for (final String imageLink : imageLinks) {
        RunnableFuture<byte[]> future = new FutureTask<>(new Callable<byte[]>() {
            @Override
            public byte[] call() {
                try {
                    URL srcUrl = new URL(imageLink);
                    URLConnection urlConnection = srcUrl.openConnection();
                    return IOUtils.toByteArray(urlConnection.getInputStream());
                } catch (IOException e) {
                    LOG.severe(e.getMessage());
                    return null;
                }
            }
        });
        service.execute(future);
        try {
            imageData.put(imageLink, Base64.encodeBase64String(future.get()));
        } catch (InterruptedException | ExecutionException e) {
            LOG.severe(e.getMessage());
        }
    }
    service.shutdown();
    try {
        service.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
        LOG.severe(e.getMessage());
    }
    return imageData;
}

From source file:com.bigdata.bop.controller.ServiceCallJoin.java

public FutureTask<Void> eval(final BOpContext<IBindingSet> context) {

    return new FutureTask<Void>(new ChunkTask(this, context));

}

From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java

/**
 * Sets a profile image for a user in the server
 *
 * @param bitmap The bitmap that should be set
 * @return <b>true</b> if the update passes, <b>false</b> if not
 *///from  w ww. ja  va 2 s  .  co m
public boolean updateUserImage(final Bitmap bitmap) {

    Callable<Boolean> booleanCallable = new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {

            HttpURLConnection conn;
            //create a json object from this submission to be sent to the server and convert it to string
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("image", LukeUtils.bitmapToBase64String(bitmap));
            String urlParameters = jsonObject.toString();

            return postMethod("http://www.balticapp.fi/lukeA/user/update", urlParameters);
        }
    };

    FutureTask<Boolean> futureTask = new FutureTask<>(booleanCallable);
    Thread t = new Thread(futureTask);
    t.start();

    try {
        return futureTask.get();
    } catch (InterruptedException | ExecutionException e) {
        Log.e(TAG, "submitToServer: ", e);
        return false;
    }
}

From source file:org.apache.tez.runtime.library.common.shuffle.impl.Shuffle.java

public void run() {
    RunShuffleCallable runShuffle = new RunShuffleCallable();
    runShuffleFuture = new FutureTask<TezRawKeyValueIterator>(runShuffle);
    new Thread(runShuffleFuture, "ShuffleMergeRunner").start();
}

From source file:com.brainflow.application.toplevel.Brainflow.java

public void launch() throws Throwable {

    try {//w w w .  j ava 2s. c  om

        String osname = System.getProperty("os.name");
        if (osname.toUpperCase().contains("WINDOWS")) {

            UIManager.setLookAndFeel(new WindowsLookAndFeel());
            //UIManager.setLookAndFeel(new com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel());

            //LookAndFeelFactory.NimbusInitializer init = new LookAndFeelFactory.NimbusInitializer();
            //init.initialize(UIManager.getDefaults());

            //UIManager.getDefaults().
            LookAndFeelFactory.installJideExtension();
            //LookAndFeelFactory.installJideExtension(LookAndFeelFactory.OFFICE2003_STYLE);
        } else if (osname.toUpperCase().contains("LINUX")) {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
            LookAndFeelFactory.installJideExtension(LookAndFeelFactory.XERTO_STYLE);

        } else {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            LookAndFeelFactory.installJideExtension();

        }

    } catch (UnsupportedLookAndFeelException e) {
        log.severe("could not load look and feel");
    }

    //final SplashScreen splash = SplashScreen.getSplashScreen();

    //JFrame.setDefaultLookAndFeelDecorated(true);

    long startTime = System.currentTimeMillis();

    brainFrame = new BrainFrame();
    statusBar = new StatusBar();
    reportTime(startTime, "created brainframe");
    brainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    log.info("initializing DisplayManager ...");
    DisplayManager.getInstance().createCanvas();

    log.info("initializing resources ...");
    FutureTask<Boolean> initResources = new FutureTask<Boolean>(new Callable<Boolean>() {
        public Boolean call() throws Exception {
            return initializeResources();
        }
    });

    threadService.execute(initResources);

    log.info("loading commands ...");
    FutureTask<Boolean> loadCommandsTask = new FutureTask<Boolean>(new Callable<Boolean>() {
        public Boolean call() throws Exception {
            return loadCommands();
        }
    });

    threadService.execute(loadCommandsTask);

    log.info("initializing IO ...");
    FutureTask<Boolean> initIOTask = new FutureTask<Boolean>(new Callable<Boolean>() {
        public Boolean call() throws Exception {
            return initImageIO();
        }
    });

    threadService.execute(initIOTask);

    log.info("initializing status bar ...");
    initializeStatusBar();
    reportTime(startTime, "initialized status bar");

    log.info("initializing work space ...");
    initializeWorkspace();
    reportTime(startTime, "initialized work space");

    loadCommandsTask.get();
    reportTime(startTime, "loaded commands");

    log.info("binding container ...");
    bindContainer();
    reportTime(startTime, "bound container");

    log.info("initializing tool bar ...");
    initializeToolBar();
    reportTime(startTime, "initialized tool bar");

    log.info("initializing menu ...");
    initializeMenu();
    reportTime(startTime, "initialized menu");

    initIOTask.get();
    reportTime(startTime, "initialized IO");

    initResources.get();
    reportTime(startTime, "initialized resources");

    initExceptionHandler();

}

From source file:uk.ac.kcl.tika.parsers.PDFPreprocessorParser.java

private File makeTiffFromPDF(File input, File output, ImageMagickConfig config)
        throws IOException, TikaException {
    String[] cmd = { config.getImageMagickPath() + getImageMagickProg(), "-density", config.getDensity(),
            input.getPath(), "-depth", config.getDepth(), "-quality", config.getQuality(), output.getPath() };

    ProcessBuilder pb = new ProcessBuilder(cmd);
    //setEnv(config, pb);
    final Process process = pb.start();

    process.getOutputStream().close();/*from   w  w  w .  ja  va2  s  .  c om*/
    InputStream out = process.getInputStream();
    InputStream err = process.getErrorStream();

    logStream("IMAGEMAGICK MSG", out, input);
    logStream("IMAGEMAGICK ERROR", err, input);

    FutureTask<Integer> waitTask = new FutureTask<Integer>(new Callable<Integer>() {
        public Integer call() throws Exception {
            return process.waitFor();
        }
    });

    Thread waitThread = new Thread(waitTask);
    waitThread.start();

    try {
        waitTask.get(config.getTimeout(), TimeUnit.SECONDS);
        return output;
    } catch (InterruptedException e) {
        waitThread.interrupt();
        process.destroy();
        Thread.currentThread().interrupt();
        throw new TikaException("ImageMagickOCRPDFParser interrupted", e);

    } catch (ExecutionException e) {
        // should not be thrown

    } catch (TimeoutException e) {
        waitThread.interrupt();
        process.destroy();
        throw new TikaException("ImageMagickOCRPDFParser timeout", e);
    }
    return null;
}

From source file:org.apache.hadoop.hbase.procedure2.RemoteProcedureDispatcher.java

protected Future<Void> submitTask(Callable<Void> task, long delay, TimeUnit unit) {
    final FutureTask<Void> futureTask = new FutureTask(task);
    timeoutExecutor.add(new DelayedTask(futureTask, delay, unit));
    return futureTask;
}

From source file:org.nuxeo.runtime.jtajca.management.CanMonitorTransactions.java

@Test
@LogCaptureFeature.FilterWith(value = CanMonitorTransactions.LogMessageFilter.class)
public void logContainsTxKey() throws InterruptedException, ExecutionException, NoLogCaptureFilterException {
    FutureTask<Boolean> task = new FutureTask<Boolean>(new TestLogRollbackTrace());
    executor.execute(task);/*from   w  ww .j a  va2  s.  c o m*/
    assertThat(task.get(), is(true));
    logCaptureResults.assertHasEvent();
}

From source file:org.yamj.filescanner.service.LibrarySendScheduler.java

/**
 * Send an ImportDTO to the core/*  w  ww  .j  a v  a  2  s  .  com*/
 *
 * Increment the running count
 *
 * @param importDto
 */
private boolean sendToCore(Library library, StageDirectoryDTO stageDir) {
    boolean sentOk = Boolean.FALSE;
    ImportDTO dto = library.getImportDTO(stageDir);

    LOG.debug("Sending #{}: {}", runningCount.incrementAndGet(), dto.getBaseDirectory());

    ApplicationContext appContext = ApplicationContextProvider.getApplicationContext();
    SendToCore stc = (SendToCore) appContext.getBean("sendToCore");
    stc.setImportDto(dto);
    stc.setCounter(runningCount);
    FutureTask<StatusType> task = new FutureTask<StatusType>(stc);

    try {
        yamjExecutor.submit(task);
        library.addDirectoryStatus(stageDir.getPath(), task);
        sentOk = Boolean.TRUE;
    } catch (TaskRejectedException ex) {
        LOG.warn("Send queue full. '{}' will be sent later.", stageDir.getPath());
        library.addDirectoryStatus(stageDir.getPath(), ConcurrentUtils.constantFuture(StatusType.NEW));
    }
    return sentOk;
}

From source file:org.apache.flink.runtime.filecache.FileCache.java

/**
 * If the file doesn't exists locally, it will copy the file to the temp directory.
 *
 * @param name  The name under which the file is registered.
 * @param entry The cache entry descriptor (path, executable flag)
 * @param jobID The ID of the job for which the file is copied.
 * @return The handle to the task that copies the file.
 *///from  w w  w  .  ja v a2  s  .  c o  m
public Future<Path> createTmpFile(String name, DistributedCacheEntry entry, JobID jobID) {
    synchronized (lock) {
        Map<String, Tuple4<Integer, File, Path, Future<Path>>> jobEntries = entries.get(jobID);
        if (jobEntries == null) {
            jobEntries = new HashMap<String, Tuple4<Integer, File, Path, Future<Path>>>();
            entries.put(jobID, jobEntries);
        }

        // tuple is (ref-count, parent-temp-dir, cached-file-path, copy-process)
        Tuple4<Integer, File, Path, Future<Path>> fileEntry = jobEntries.get(name);
        if (fileEntry != null) {
            // file is already in the cache. return a future that
            // immediately returns the file
            fileEntry.f0 = fileEntry.f0 + 1;

            // return the future. may be that the copy is still in progress
            return fileEntry.f3;
        } else {
            // need to copy the file

            // create the target path
            File tempDirToUse = new File(storageDirectories[nextDirectory++], jobID.toString());
            if (nextDirectory >= storageDirectories.length) {
                nextDirectory = 0;
            }

            String sourceFile = entry.filePath;
            int posOfSep = sourceFile.lastIndexOf("/");
            if (posOfSep > 0) {
                sourceFile = sourceFile.substring(posOfSep + 1);
            }

            Path target = new Path(tempDirToUse.getAbsolutePath() + "/" + sourceFile);

            // kick off the copying
            CopyProcess cp = new CopyProcess(entry, target);
            FutureTask<Path> copyTask = new FutureTask<Path>(cp);
            executorService.submit(copyTask);

            // store our entry
            jobEntries.put(name,
                    new Tuple4<Integer, File, Path, Future<Path>>(1, tempDirToUse, target, copyTask));

            return copyTask;
        }
    }
}