List of usage examples for com.google.common.util.concurrent ListenableFutureTask create
public static <V> ListenableFutureTask<V> create(Callable<V> callable)
From source file:com.vmware.photon.controller.clustermanager.tasks.VmProvisionTaskService.java
/** * Attaches an ISO to the created VM. The ISO attached * contains the Cloud-Init configuration as specified through the template files passed-in the task. * On success, the task is moved to the next sub-stage i.e. START_VM * * @param currentState// w w w .j a va2 s . c om */ private void createIsoFile(final State currentState) throws Throwable { final File isoFile = new File("/tmp", CONFIG_FILENAME + "-" + currentState.vmId + ".iso"); final File userDataConfigFile = new File(HostUtils.getScriptsDirectory(this), CONFIG_FILENAME + "-user-data-" + currentState.vmId + ".yml"); final File metaDataConfigFile = new File(HostUtils.getScriptsDirectory(this), CONFIG_FILENAME + "-meta-data-" + currentState.vmId + ".yml"); File scriptLogFile = new File(HostUtils.getScriptsDirectory(this), SCRIPT_NAME + "-" + currentState.vmId + ".log"); String userDataConfigFilename = createFile(currentState.userData, userDataConfigFile); String metaDataConfigFilename = createFile(currentState.metaData, metaDataConfigFile); List<String> command = new ArrayList<>(); command.add("/bin/bash"); command.add("./" + SCRIPT_NAME); command.add(isoFile.getAbsolutePath()); command.add(userDataConfigFilename); command.add(metaDataConfigFilename); ScriptRunner scriptRunner = new ScriptRunner.Builder(command, ClusterManagerConstants.SCRIPT_TIMEOUT_IN_SECONDS).directory(HostUtils.getScriptsDirectory(this)) .redirectOutput(ProcessBuilder.Redirect.to(scriptLogFile)).build(); ListenableFutureTask<Integer> futureTask = ListenableFutureTask.create(scriptRunner); HostUtils.getListeningExecutorService(this).submit(futureTask); FutureCallback<Integer> futureCallback = new FutureCallback<Integer>() { @Override public void onSuccess(@Nullable Integer result) { if (null == result) { failTask(new NullPointerException(SCRIPT_NAME + " returned null")); } else if (0 != result) { failTask(new Exception(SCRIPT_NAME + " returned " + result.toString())); } else { try { Files.deleteIfExists(userDataConfigFile.toPath()); Files.deleteIfExists(metaDataConfigFile.toPath()); attachAndUploadIso(currentState, isoFile.getAbsolutePath()); } catch (IOException e) { failTask(e); } } } @Override public void onFailure(Throwable t) { failTask(t); } }; Futures.addCallback(futureTask, futureCallback); }
From source file:org.waveprotocol.box.server.search.LuceneSearchImpl.java
private ListenableFutureTask<Void> sheduleUpdateIndex(final WaveId waveId) { synchronized (indexingWaves) { ListenableFutureTask<Void> task = indexingWaves.get(waveId); if (task == null) { task = ListenableFutureTask.create(new Callable<Void>() { @Override// ww w .j av a 2 s.co m public Void call() throws Exception { indexingWaves.remove(waveId); try { updateIndex(waveId); } catch (IndexingInProcessException e) { sheduleUpdateIndex(waveId); } catch (Throwable e) { LOG.log(Level.SEVERE, "Failed to update index for " + waveId.serialise(), e); throw e; } return null; } }); indexingWaves.put(waveId, task); indexExecutor.schedule(task, WAVE_INDEXING_DELAY_SEC, TimeUnit.SECONDS); } return task; } }
From source file:at.d4muck.fireworm.repository.Database.java
public <T> Task<T> get(final String id, final Class<T> modelClass) { ListenableFutureTask<T> futureTask = ListenableFutureTask .create(new DatabaseSingleGetCallable<T>(id, modelClass)); executor.execute(futureTask);/*w ww . ja v a2 s. c om*/ final DatabaseGetTask<T> databaseGetTask = new DatabaseGetTask<>(); Futures.addCallback(futureTask, new FutureCallback<T>() { @Override public void onSuccess(T result) { databaseGetTask.setResult(result); } @Override public void onFailure(Throwable t) { databaseGetTask.setException(t); } }, mainLooperExecutor); return databaseGetTask; }
From source file:io.fabric8.process.manager.support.command.Command.java
private static <T> ListenableFuture<T> submit(Executor executor, Callable<T> task) { ListenableFutureTask<T> future = ListenableFutureTask.create(task); executor.execute(future);//from www.ja v a 2 s.c o m return future; }
From source file:com.comcast.cdn.traffic_control.traffic_router.core.dns.ZoneManager.java
private static LoadingCache<ZoneKey, Zone> createZoneCache(final ZoneCacheType cacheType, final CacheBuilderSpec spec) { final RemovalListener<ZoneKey, Zone> removalListener = new RemovalListener<ZoneKey, Zone>() { public void onRemoval(final RemovalNotification<ZoneKey, Zone> removal) { LOGGER.debug(cacheType + " " + removal.getKey().getClass().getSimpleName() + " " + removal.getKey().getName() + " evicted from cache: " + removal.getCause()); }//from w ww .ja va2 s.co m }; return CacheBuilder.from(spec).recordStats().removalListener(removalListener) .build(new CacheLoader<ZoneKey, Zone>() { final boolean writeZone = (cacheType == ZoneCacheType.STATIC) ? true : false; public Zone load(final ZoneKey zoneKey) throws IOException, GeneralSecurityException { LOGGER.debug("loading " + cacheType + " " + zoneKey.getClass().getSimpleName() + " " + zoneKey.getName()); return loadZone(zoneKey, writeZone); } public ListenableFuture<Zone> reload(final ZoneKey zoneKey, final Zone prevZone) throws IOException, GeneralSecurityException { final ListenableFutureTask<Zone> zoneTask = ListenableFutureTask .create(new Callable<Zone>() { public Zone call() throws IOException, GeneralSecurityException { return loadZone(zoneKey, writeZone); } }); zoneExecutor.execute(zoneTask); return zoneTask; } }); }
From source file:com.vmware.photon.controller.clustermanager.tasks.VmProvisionTaskService.java
private void attachAndUploadIso(final State currentState, final String isoFile) throws IOException { final ApiClient client = HostUtils.getApiClient(this); ListenableFutureTask<Task> futureTask = ListenableFutureTask.create(() -> { try {//from w ww .ja v a2 s . co m return client.getVmApi().uploadAndAttachIso(currentState.vmId, isoFile); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }); HostUtils.getListeningExecutorService(this).submit(futureTask); FutureCallback<Task> futureCallback = new FutureCallback<Task>() { @Override public void onSuccess(@Nullable Task result) { try { if (null == result) { failTask(new IllegalStateException("IsoUploadAndAttach returned null")); return; } Files.deleteIfExists(Paths.get(isoFile)); processTask(result, currentState, buildPatch(TaskState.TaskStage.STARTED, State.TaskState.SubStage.START_VM)); } catch (Throwable e) { failTask(e); } } @Override public void onFailure(Throwable t) { failTask(t); } }; Futures.addCallback(futureTask, futureCallback); }
From source file:org.waveprotocol.box.server.search.LuceneSearchImpl.java
private ListenableFutureTask<Void> sheduleCommitIndex() { ListenableFutureTask<Void> task = commitTask.get(); if (task == null) { task = ListenableFutureTask.create(new Callable<Void>() { @Override//from w w w. ja va 2s . c om public Void call() throws Exception { commitTask.set(null); try { LOG.info("Commiting indexes..."); indexWriter.commit(); LOG.info("Commiting indexes is complete"); } catch (IndexException e) { LOG.log(Level.SEVERE, "Index commit failed", e); throw e; } return null; } }); commitTask.set(task); indexExecutor.schedule(task, WAVE_COMMIT_DELAY_SEC, TimeUnit.SECONDS); } return task; }
From source file:com.tinspx.util.concurrent.ThreadUtils.java
/** * Creates a {@code ListenableFutureTask} that waits the for the latch to * reach 0 through {@link CountDownLatch#await()}. The Future result is set * to null once the latch reaches 0.//from w w w . j av a2 s . c o m * * @param latch {@code CountDownLatch} to await * @return a task that calls {@link CountDownLatch#await() latch.await()} */ public static <T> ListenableFutureTask<T> newLatchAwaitor(final CountDownLatch latch) { checkNotNull(latch); return ListenableFutureTask.create(new Callable<T>() { @Override public T call() throws Exception { latch.await(); return null; } }); }
From source file:com.android.tools.idea.profiling.capture.CaptureService.java
/** * Closes the file and asynchronously returns the generated {@code Capture} on the EDT within the given {@code onCompletion} callback. * * @param captureHandle is the handle returned by {@link #startCaptureFile(Class)} * @param onCompletion will be called when the asynchronous closing of the file and generating the {@code Capture} is completed or error'ed * @param executor is the executor to run the onCompletion callbacks *//*from w w w .ja va 2 s . com*/ public void finalizeCaptureFileAsynchronous(@NotNull final CaptureHandle captureHandle, @Nullable FutureCallback<Capture> onCompletion, @Nullable Executor executor) { final ListenableFutureTask<Capture> postCloseTask = ListenableFutureTask.create(new Callable<Capture>() { @Override public Capture call() throws Exception { ApplicationManager.getApplication().assertIsDispatchThread(); if (captureHandle.getWriteToTempFile()) { ApplicationManager.getApplication() .runWriteAction(new ThrowableComputable<Object, IOException>() { @Override public Object compute() throws IOException { String tempFilePath = captureHandle.getFile().getCanonicalPath(); assert tempFilePath.endsWith(TEMP_FILE_EXTENSION); String originalFilePath = tempFilePath.substring(0, tempFilePath.length() - TEMP_FILE_EXTENSION.length()); captureHandle.move(new File(originalFilePath)); return null; } }); } return createCapture(captureHandle); } }); if (onCompletion != null) { assert executor != null; Futures.addCallback(postCloseTask, onCompletion, executor); } closeCaptureFileInternal(captureHandle, new Runnable() { @Override public void run() { ApplicationManager.getApplication().invokeLater(postCloseTask); } }); }
From source file:com.tinspx.util.concurrent.ThreadUtils.java
/** * Creates a {@code ListenableFutureTask} that waits for the thread to die * through {@link Thread#join()}. The Future result is set to null once the * thread is dead./* w w w . j a va 2s .c o m*/ * * @param thread the Thread to join * @return a task that calls {@link Thread#join() thread.join()} */ public static <T> ListenableFutureTask<T> newThreadJoiner(final Thread thread) { checkNotNull(thread); return ListenableFutureTask.create(new Callable<T>() { @Override public T call() throws Exception { thread.join(); return null; } }); }