Java Code Examples for com.google.common.util.concurrent.ListenableFutureTask#create()

The following examples show how to use com.google.common.util.concurrent.ListenableFutureTask#create() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LucenePerUserWaveViewHandlerImpl.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<Void> onParticipantAdded(final WaveletName waveletName,
    ParticipantId participant) {
  Preconditions.checkNotNull(waveletName);
  Preconditions.checkNotNull(participant);

  ListenableFutureTask<Void> task = ListenableFutureTask.create(new Callable<Void>() {

    @Override
    public Void call() throws Exception {
      ReadableWaveletData waveletData;
      try {
        waveletData = waveletProvider.getReadableWaveletData(waveletName);
        updateIndex(waveletData);
      } catch (WaveServerException e) {
        LOG.log(Level.SEVERE, "Failed to update index for " + waveletName, e);
        throw e;
      }
      return null;
    }
  });
  executor.execute(task);
  return task;
}
 
Example 2
Source File: LucenePerUserWaveViewHandlerImpl.java    From swellrt with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<Void> onParticipantAdded(final WaveletName waveletName,
    ParticipantId participant) {
  Preconditions.checkNotNull(waveletName);
  Preconditions.checkNotNull(participant);

  ListenableFutureTask<Void> task = ListenableFutureTask.create(new Callable<Void>() {

    @Override
    public Void call() throws Exception {
      ReadableWaveletData waveletData;
      try {
        waveletData = waveletProvider.getReadableWaveletData(waveletName);
        updateIndex(waveletData);
      } catch (WaveServerException e) {
        LOG.log(Level.SEVERE, "Failed to update index for " + waveletName, e);
        throw e;
      }
      return null;
    }
  });
  executor.execute(task);
  return task;
}
 
Example 3
Source File: WaveServerModule.java    From swellrt with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a future whose result is the state of the wavelet after it has been
 * loaded from storage. Any failure is reported as a
 * {@link PersistenceException}.
 */
@VisibleForTesting
static ListenableFuture<DeltaStoreBasedWaveletState> loadWaveletState(Executor executor,
    final DeltaStore deltaStore, final DeltaStoreTransient transientDeltaStore,
    final WaveletName waveletName, final Executor persistExecutor,
    final int persistSnapshotOnDeltasCount) {
  ListenableFutureTask<DeltaStoreBasedWaveletState> task = ListenableFutureTask
      .create(new Callable<DeltaStoreBasedWaveletState>() {
        @Override
        public DeltaStoreBasedWaveletState call() throws PersistenceException {

          DeltasAccess deltasAccess = null;
          if (waveletName.waveletId.isTransientWavelet())
            deltasAccess = transientDeltaStore.open(waveletName);
          else
            deltasAccess = deltaStore.open(waveletName);

          return DeltaStoreBasedWaveletState.create(deltasAccess, persistExecutor,
              persistSnapshotOnDeltasCount);
        }
      });
  executor.execute(task);
  return task;
}
 
Example 4
Source File: SolrWaveIndexerImpl.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<Void> onWaveInit(final WaveletName waveletName) {

  ListenableFutureTask<Void> task = ListenableFutureTask.create(new Callable<Void>() {

    @Override
    public Void call() throws Exception {
      ReadableWaveletData waveletData;
      try {
        waveletData = waveletDataProvider.getReadableWaveletData(waveletName);
        updateIndex(waveletData);
      } catch (WaveServerException e) {
        LOG.log(Level.SEVERE, "Failed to initialize index for " + waveletName, e);
        throw e;
      }
      return null;
    }
  });
  executor.execute(task);
  return task;
}
 
Example 5
Source File: SolrWaveIndexerImpl.java    From swellrt with Apache License 2.0 6 votes vote down vote up
@Override
public void waveletCommitted(final WaveletName waveletName, final HashedVersion version) {

  Preconditions.checkNotNull(waveletName);

  ListenableFutureTask<Void> task = ListenableFutureTask.create(new Callable<Void>() {

    @Override
    public Void call() throws Exception {
      ReadableWaveletData waveletData;
      try {
        waveletData = waveletDataProvider.getReadableWaveletData(waveletName);
        LOG.fine("commit " + version + " " + waveletData.getVersion());
        if (waveletData.getVersion() == version.getVersion()) {
          updateIndex(waveletData);
        }
      } catch (WaveServerException e) {
        LOG.log(Level.SEVERE, "Failed to update index for " + waveletName, e);
        throw e;
      }
      return null;
    }
  });
  executor.execute(task);
}
 
Example 6
Source File: LucenePerUserWaveViewHandlerImpl.java    From swellrt with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<Void> onWaveInit(final WaveletName waveletName) {
  Preconditions.checkNotNull(waveletName);

  ListenableFutureTask<Void> task = ListenableFutureTask.create(new Callable<Void>() {

    @Override
    public Void call() throws Exception {
      ReadableWaveletData waveletData;
      try {
        waveletData = waveletProvider.getReadableWaveletData(waveletName);
        updateIndex(waveletData);
      } catch (WaveServerException e) {
        LOG.log(Level.SEVERE, "Failed to initialize index for " + waveletName, e);
        throw e;
      }
      return null;
    }
  });
  executor.execute(task);
  return task;
}
 
Example 7
Source File: Scheduler.java    From The-5zig-Mod with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Posts a runnable to the Main Server Thread.
 * <p/>
 *
 * @param runnable The runnable that should be executed.
 * @return a Listenable Future.
 */
public ListenableFuture postToMainThread(Runnable runnable, boolean noThreadCheck, int delay) {
	Callable callable = Executors.callable(runnable);
	ListenableFuture listenableFuture = ListenableFutureTask.create(callable);
	if (noThreadCheck || delay > 0 || !The5zigMod.getVars().isMainThread()) {
		synchronized (jobs) {
			jobs.add(new Task(listenableFuture, delay));
			return listenableFuture;
		}
	} else {
		try {
			return Futures.immediateFuture(callable.call());
		} catch (Exception e) {
			return Futures.immediateFailedCheckedFuture(e);
		}
	}
}
 
Example 8
Source File: SolrWaveIndexerImpl.java    From swellrt with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<Void> onWaveInit(final WaveletName waveletName) {

  ListenableFutureTask<Void> task = ListenableFutureTask.create(new Callable<Void>() {

    @Override
    public Void call() throws Exception {
      ReadableWaveletData waveletData;
      try {
        waveletData = waveletDataProvider.getReadableWaveletData(waveletName);
        updateIndex(waveletData);
      } catch (WaveServerException e) {
        LOG.log(Level.SEVERE, "Failed to initialize index for " + waveletName, e);
        throw e;
      }
      return null;
    }
  });
  executor.execute(task);
  return task;
}
 
Example 9
Source File: Scheduler.java    From The-5zig-Mod with MIT License 6 votes vote down vote up
/**
 * Posts a runnable to the Main Server Thread.
 * <p/>
 *
 * @param runnable The runnable that should be executed.
 * @return a Listenable Future.
 */
public ListenableFuture postToMainThread(Runnable runnable, boolean noThreadCheck, int delay) {
	Callable callable = Executors.callable(runnable);
	ListenableFuture listenableFuture = ListenableFutureTask.create(callable);
	if (noThreadCheck || delay > 0 || !The5zigMod.getVars().isMainThread()) {
		synchronized (jobs) {
			jobs.add(new Task(listenableFuture, delay));
			return listenableFuture;
		}
	} else {
		try {
			return Futures.immediateFuture(callable.call());
		} catch (Exception e) {
			return Futures.immediateFailedCheckedFuture(e);
		}
	}
}
 
Example 10
Source File: SolrWaveIndexerImpl.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
@Override
public void waveletCommitted(final WaveletName waveletName, final HashedVersion version) {

  Preconditions.checkNotNull(waveletName);

  ListenableFutureTask<Void> task = ListenableFutureTask.create(new Callable<Void>() {

    @Override
    public Void call() throws Exception {
      ReadableWaveletData waveletData;
      try {
        waveletData = waveletDataProvider.getReadableWaveletData(waveletName);
        LOG.fine("commit " + version + " " + waveletData.getVersion());
        if (waveletData.getVersion() == version.getVersion()) {
          updateIndex(waveletData);
        }
      } catch (WaveServerException e) {
        LOG.log(Level.SEVERE, "Failed to update index for " + waveletName, e);
        throw e;
      }
      return null;
    }
  });
  executor.execute(task);
}
 
Example 11
Source File: Hive.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected synchronized ListenableFuture<Void> performAddConnection ( final String id, final ConnectionConfiguration configuration )
{
    logger.debug ( "adding connection - id: {}, cfg: {}", id, configuration );

    if ( this.executor == null )
    {
        logger.debug ( "Hive is not started" );
        return Futures.immediateFailedFuture ( new IllegalStateException ( "Hive is not started" ) );
    }

    final ListenableFutureTask<Void> task = ListenableFutureTask.create ( new Callable<Void> () {

        @Override
        public Void call () throws Exception
        {
            try
            {
                handleAddConnection ( id, configuration );
            }
            catch ( final Exception e )
            {
                logger.warn ( "Failed to create connection", e );
                throw new InvocationTargetException ( e );
            }
            return null;
        }
    } );
    this.executor.execute ( task );
    return task;
}
 
Example 12
Source File: PhotosLibraryUploadUnaryCallable.java    From java-photoslibrary with Apache License 2.0 5 votes vote down vote up
public static final PhotosLibraryUploadApiFuture create(
    PhotosLibraryUploadCallable uploadCallable, ClientContext clientContext) {
  PhotosLibraryUploadApiFuture future =
      new PhotosLibraryUploadApiFuture(ListenableFutureTask.create(uploadCallable));
  clientContext.getExecutor().execute(future.futureTask);
  return future;
}
 
Example 13
Source File: ChunkRenderDispatcherLitematica.java    From litematica with GNU Lesser General Public License v3.0 5 votes vote down vote up
public ListenableFuture<Object> uploadChunkOverlay(final OverlayRenderType type, final BufferBuilder buffer,
        final RenderChunkSchematicVbo renderChunk, final CompiledChunkSchematic compiledChunk, final double distanceSq)
{
    if (Minecraft.getMinecraft().isCallingFromMinecraftThread())
    {
        //if (GuiBase.isCtrlDown()) System.out.printf("uploadChunkOverlay()\n");
        if (OpenGlHelper.useVbo())
        {
            this.uploadVertexBuffer(buffer, renderChunk.getOverlayVertexBuffer(type));
        }
        else
        {
            this.uploadDisplayList(buffer, ((RenderChunkSchematicList) renderChunk).getOverlayDisplayList(type, compiledChunk), renderChunk);
        }

        buffer.setTranslation(0.0D, 0.0D, 0.0D);

        return Futures.<Object>immediateFuture(null);
    }
    else
    {
        ListenableFutureTask<Object> futureTask = ListenableFutureTask.<Object>create(new Runnable()
        {
            @Override
            public void run()
            {
                ChunkRenderDispatcherLitematica.this.uploadChunkOverlay(type, buffer, renderChunk, compiledChunk, distanceSq);
            }
        }, null);

        synchronized (this.queueChunkUploads)
        {
            this.queueChunkUploads.add(new ChunkRenderDispatcherLitematica.PendingUpload(futureTask, distanceSq));
            return futureTask;
        }
    }
}
 
Example 14
Source File: ChunkRenderDispatcherLitematica.java    From litematica with GNU Lesser General Public License v3.0 5 votes vote down vote up
public ListenableFuture<Object> uploadChunkBlocks(final BlockRenderLayer layer, final BufferBuilder buffer,
        final RenderChunkSchematicVbo renderChunk, final CompiledChunk compiledChunk, final double distanceSq)
{
    if (Minecraft.getMinecraft().isCallingFromMinecraftThread())
    {
        //if (GuiBase.isCtrlDown()) System.out.printf("uploadChunkBlocks()\n");
        if (OpenGlHelper.useVbo())
        {
            this.uploadVertexBuffer(buffer, renderChunk.getVertexBufferByLayer(layer.ordinal()));
        }
        else
        {
            this.uploadDisplayList(buffer, ((RenderChunkSchematicList) renderChunk).getDisplayList(layer, compiledChunk), renderChunk);
        }

        buffer.setTranslation(0.0D, 0.0D, 0.0D);

        return Futures.<Object>immediateFuture(null);
    }
    else
    {
        ListenableFutureTask<Object> futureTask = ListenableFutureTask.<Object>create(new Runnable()
        {
            @Override
            public void run()
            {
                ChunkRenderDispatcherLitematica.this.uploadChunkBlocks(layer, buffer, renderChunk, compiledChunk, distanceSq);
            }
        }, null);

        synchronized (this.queueChunkUploads)
        {
            this.queueChunkUploads.add(new ChunkRenderDispatcherLitematica.PendingUpload(futureTask, distanceSq));
            return futureTask;
        }
    }
}
 
Example 15
Source File: NodeShardCacheImpl.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<CacheEntry> reload( final CacheKey key, final CacheEntry oldValue ) throws Exception {
    ListenableFutureTask<CacheEntry> task = ListenableFutureTask.create( new Callable<CacheEntry>() {
        public CacheEntry call() {
            return load( key );
        }
    } );
    //load via the refresh executor
    refreshExecutors.execute( task );
    return task;
}
 
Example 16
Source File: DeltaStoreBasedWaveletState.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<Void> persist(final HashedVersion version) {
  Preconditions.checkArgument(version.getVersion() > 0,
      "Cannot persist non-positive version %s", version);
  Preconditions.checkArgument(isDeltaBoundary(version),
      "Version to persist %s matches no delta", version);
  synchronized (persistLock) {
    if (latestVersionToPersist != null) {
      // There's a persist task in flight.
      if (version.getVersion() <= latestVersionToPersist.getVersion()) {
        LOG.info("Attempt to persist version " + version
            + " smaller than last version requested " + latestVersionToPersist);
      } else {
        latestVersionToPersist = version;
      }
      if (nextPersistTask == null) {
        nextPersistTask = ListenableFutureTask.<Void>create(persisterTask);
      }
      return nextPersistTask;
    } else {
      latestVersionToPersist = version;
      ListenableFutureTask<Void> resultTask = ListenableFutureTask.<Void>create(persisterTask);
      persistExecutor.execute(resultTask);
      return resultTask;
    }
  }
}
 
Example 17
Source File: LongBTreeTest.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
private static ListenableFutureTask<List<ListenableFuture<?>>> doOneTestInsertions(final int upperBound, final int maxRunLength, final int averageModsPerIteration, final int iterations, final boolean quickEquality)
{
    ListenableFutureTask<List<ListenableFuture<?>>> f = ListenableFutureTask.create(new Callable<List<ListenableFuture<?>>>()
    {
        @Override
        public List<ListenableFuture<?>> call()
        {
            final List<ListenableFuture<?>> r = new ArrayList<>();
            NavigableMap<Integer, Integer> canon = new TreeMap<>();
            Object[] btree = BTree.empty();
            final TreeMap<Integer, Integer> buffer = new TreeMap<>();
            final Random rnd = new Random();
            for (int i = 0 ; i < iterations ; i++)
            {
                buffer.clear();
                int mods = (averageModsPerIteration >> 1) + 1 + rnd.nextInt(averageModsPerIteration);
                while (mods > 0)
                {
                    int v = rnd.nextInt(upperBound);
                    int rc = Math.max(0, Math.min(mods, maxRunLength) - 1);
                    int c = 1 + (rc <= 0 ? 0 : rnd.nextInt(rc));
                    for (int j = 0 ; j < c ; j++)
                    {
                        buffer.put(v, v);
                        v++;
                    }
                    mods -= c;
                }
                TimerContext ctxt;
                ctxt = TREE_TIMER.time();
                canon.putAll(buffer);
                ctxt.stop();
                ctxt = BTREE_TIMER.time();
                Object[] next = null;
                while (next == null)
                    next = BTree.update(btree, ICMP, buffer.keySet(), true, SPORADIC_ABORT);
                btree = next;
                ctxt.stop();

                if (!BTree.isWellFormed(btree, ICMP))
                {
                    System.out.println("ERROR: Not well formed");
                    throw new AssertionError("Not well formed!");
                }
                if (quickEquality)
                    testEqual("", BTree.<Integer>slice(btree, true), canon.keySet().iterator());
                else
                    r.addAll(testAllSlices("RND", btree, new TreeSet<>(canon.keySet())));
            }
            return r;
        }
    });
    MODIFY.execute(f);
    return f;
}
 
Example 18
Source File: MockLoader.java    From datawave with Apache License 2.0 3 votes vote down vote up
public ListenableFuture<InMemoryInstance> reload(LoaderKey key, InMemoryInstance oldValue) throws Exception {
    
    ListenableFutureTask<InMemoryInstance> task = ListenableFutureTask.create(new TableCallable(key));
    
    executorService.execute(task);
    
    return task;
    
}
 
Example 19
Source File: Producers.java    From dagger2-sample with Apache License 2.0 2 votes vote down vote up
/**
 * Submits a callable to an executor, returning the future representing the task. This mirrors
 * {@link com.google.common.util.concurrent.ListeningExecutorService#submit}, but only requires an
 * {@link Executor}.
 *
 * @throws RejectedExecutionException if this task cannot be accepted for execution.
 */
public static <T> ListenableFuture<T> submitToExecutor(Callable<T> callable, Executor executor) {
  ListenableFutureTask<T> future = ListenableFutureTask.create(callable);
  executor.execute(future);
  return future;
}
 
Example 20
Source File: QueryScheduler.java    From incubator-pinot with Apache License 2.0 2 votes vote down vote up
/**
 * Create a future task for the query
 * @param queryRequest incoming query request
 * @param executorService executor service to use for parallelizing query. This is passed to the QueryExecutor
 * @return Future task that can be scheduled for execution on an ExecutorService. Ideally, this future
 * should be executed on a different executor service than {@code e} to avoid deadlock.
 */
protected ListenableFutureTask<byte[]> createQueryFutureTask(@Nonnull ServerQueryRequest queryRequest,
    @Nonnull ExecutorService executorService) {
  return ListenableFutureTask.create(() -> processQueryAndSerialize(queryRequest, executorService));
}