Example usage for com.google.common.util.concurrent MoreExecutors sameThreadExecutor

List of usage examples for com.google.common.util.concurrent MoreExecutors sameThreadExecutor

Introduction

In this page you can find the example usage for com.google.common.util.concurrent MoreExecutors sameThreadExecutor.

Prototype

@Deprecated
@GwtIncompatible("TODO")
public static ListeningExecutorService sameThreadExecutor() 

Source Link

Document

Creates an executor service that runs each task in the thread that invokes execute/submit , as in CallerRunsPolicy .

Usage

From source file:com.yahoo.yqlplus.engine.internal.java.runtime.TimeoutHandler.java

public <T> ListenableFuture<T> withTimeout(final ListenableFuture<T> source, long timeout,
        TimeUnit timeoutUnits) {/*w w w .ja v a 2s  .c  o  m*/
    if (timeout != 0) {
        final SettableFuture<T> result = SettableFuture.create();
        final Future<?> scheduledFuture = timers
                .schedule(new TimeoutTask<T>(source, result, timeout, timeoutUnits), timeout, timeoutUnits);
        result.addListener(new Runnable() {
            @Override
            public void run() {
                scheduledFuture.cancel(false);
                if (result.isCancelled()) {
                    source.cancel(true);
                }
            }
        }, MoreExecutors.sameThreadExecutor());
        Futures.addCallback(source, new FutureCallback<T>() {
            @Override
            public void onSuccess(T out) {
                scheduledFuture.cancel(false);
                result.set(out);
            }

            @Override
            public void onFailure(Throwable t) {
                scheduledFuture.cancel(false);
                result.setException(t);
            }
        });
        return scoper.scopeCallbacks(result);
    } else {
        return source;
    }
}

From source file:org.erlide.runtime.internal.OtpNodeProxy.java

public OtpNodeProxy(final RuntimeData data) {
    this.data = data;
    reporter = new ErlRuntimeReporter(data.isInternal());

    eventHelper = new EventParser();
    final String nodeName = getNodeName();
    eventBus = new EventBus(nodeName);
    eventBus.register(this);
    registerEventListener(new LogEventHandler());
    registerEventListener(new ErlangLogEventHandler());

    final Provider<Service> factory = new Provider<Service>() {
        @Override/*  w w  w.  j a  v a 2 s  .co m*/
        public Service get() {
            return new OtpNodeProxyService(data.isManaged());
        }
    };

    ServiceRestartPolicy policy;
    if (data.isRestartable()) {
        policy = new CooldownRestartPolicy(6000);
    } else {
        policy = new NeverRestartPolicy();
    }

    service = new RestartableService(factory, policy);
    service.addListener(new ErlRuntimeListener(), MoreExecutors.sameThreadExecutor());
}

From source file:org.erlide.runtime.OtpNodeProxy.java

public OtpNodeProxy(final RuntimeData data) {
    this.data = data;
    reporter = new ErlRuntimeReporter(data.isInternal());

    eventHelper = new EventParser();
    final String nodeName = getNodeName();
    eventBus = new EventBus(nodeName);
    eventBus.register(this);
    registerEventListener(new LogEventHandler(nodeName));
    registerEventListener(new ErlangLogEventHandler(nodeName));

    final Provider<Service> factory = new Provider<Service>() {
        @Override//from www  . ja v a  2 s.  c  o  m
        public Service get() {
            return new OtpNodeProxyService(data.isManaged());
        }
    };

    ServiceRestartPolicy policy;
    if (data.isRestartable()) {
        policy = new CooldownRestartPolicy(6000);
    } else {
        policy = new NeverRestartPolicy();
    }

    service = new RestartableService(factory, policy);
    service.addListener(new ErlRuntimeListener(), MoreExecutors.sameThreadExecutor());
}

From source file:net.techcable.spawnshield.forcefield.ForceFieldListener.java

@EventHandler(priority = EventPriority.MONITOR)
public void onMove(PlayerMoveEvent event) {
    if (event.getFrom().equals(event.getTo()))
        return; //Don't wanna fire if the player turned his head
    if (currentlyProcessing.contains(event.getPlayer().getUniqueId()))
        return;/*from  www  .  ja  v a2 s  . c o  m*/
    final SpawnShieldPlayer player = plugin.getPlayer(event.getPlayer());
    if (!plugin.getCombatTagPlugin().isTagged(event.getPlayer())) {
        if (player.getLastShownBlocks() != null && !currentlyProcessing.contains(player.getId())) {
            currentlyProcessing.add(player.getId());
            new BukkitRunnable() {
                @Override
                public void run() {
                    for (BlockPos lastShown : player.getLastShownBlocks()) {
                        player.getEntity().sendBlockChange(lastShown.toLocation(), lastShown.getTypeAt(),
                                lastShown.getDataAt());
                    }
                    player.setLastShownBlocks(null);
                    currentlyProcessing.remove(player.getId());
                }
            }.runTaskAsynchronously(plugin);
        }
        return;
    }
    currentlyProcessing.add(player.getId());
    BlockPos pos = new BlockPos(player.getEntity().getLocation());
    Collection<Region> toUpdate = new HashSet<>();
    for (Region region : plugin.getSettings().getRegionsToBlock()) {
        if (!region.getWorld().equals(event.getPlayer().getWorld()))
            continue; //We dont need this one: Yay!
        toUpdate.add(region);
    }
    ForceFieldUpdateRequest request = new ForceFieldUpdateRequest(pos, toUpdate, player,
            plugin.getSettings().getForcefieldRange());
    final ForceFieldUpdateTask task = new ForceFieldUpdateTask(plugin, request);
    Bukkit.getScheduler().runTaskAsynchronously(plugin, task);
    task.addListener(new Runnable() {
        @Override
        public void run() {
            currentlyProcessing.remove(player.getId());
        }
    }, MoreExecutors.sameThreadExecutor());
}

From source file:test.mock.util.DataBrokerTestCustomizer.java

public ForwardedBackwardsCompatibleDataBroker createBackwardsCompatibleDataBroker() {
    return new ForwardedBackwardsCompatibleDataBroker(getDOMDataBroker(), bindingToNormalized,
            getSchemaService(), MoreExecutors.sameThreadExecutor());
}

From source file:com.google.idea.common.experiments.WebExperimentSyncer.java

private void scheduleNextRefresh(boolean refreshWasSuccessful) {
    int delayInMinutes = refreshWasSuccessful ? SUCESSFUL_DOWNLOAD_DELAY_MINUTES
            : DOWNLOAD_FAILURE_DELAY_MINUTES;
    ListenableScheduledFuture<String> refreshResults = executor.schedule(new WebExperimentsDownloader(),
            delayInMinutes, TimeUnit.MINUTES);
    refreshResults.addListener(new WebExperimentsResultProcessor(refreshResults),
            MoreExecutors.sameThreadExecutor());
}

From source file:diskCacheV111.srm.dcache.SrmReleaseSpaceCompanion.java

public static void releaseSpace(Subject subject, String spaceToken, Long spaceToReleaseInBytes,
        SrmReleaseSpaceCallback callback, CellStub spaceManagerStub) {
    LOGGER.trace("SrmReleaseSpaceCompanion.releaseSpace({}, token {}, spaceToReleaseInBytes {})",
            subject.getPrincipals(), spaceToken, spaceToReleaseInBytes);
    try {//w w  w  . ja  va 2  s . c  o  m
        long token = Long.parseLong(spaceToken);
        SrmReleaseSpaceCompanion companion = new SrmReleaseSpaceCompanion(callback);
        Release release = new Release(token, spaceToReleaseInBytes);
        release.setSubject(subject);
        CellStub.addCallback(spaceManagerStub.send(release), companion, MoreExecutors.sameThreadExecutor());
    } catch (NumberFormatException e) {
        callback.invalidRequest("No such space");
    }
}

From source file:co.cask.tigon.sql.manager.ExternalProgramExecutor.java

@Override
protected void startUp() throws Exception {
    // We need two threads.
    // One thread for keep reading from input, write to process stdout and read from stdin.
    // The other for keep reading stderr and log.
    executor = Executors.newFixedThreadPool(2,
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat("process-" + name + "-%d").build());

    // the Shutdown thread is to time the shutdown and kill the process if it timeout.
    shutdownThread = createShutdownThread();

    if (name.toLowerCase().contains("rts")) {
        this.addListener(new RTSGarbageCollector(), MoreExecutors.sameThreadExecutor());
    }/* w w w. j  ava2  s  . com*/

    List<String> cmd = ImmutableList.<String>builder().add(executable.toURI().getPath()).add(args).build();
    process = new ProcessBuilder(cmd).directory(workingDir).start();
    executor.execute(createProcessRunnable(process));
    executor.execute(createLogRunnable(process));

    //Get Process ID of the initiated process
    try {
        Field f = process.getClass().getDeclaredField("pid");
        f.setAccessible(true);
        pid = Integer.toString(f.getInt(process));
    } catch (Throwable e) {
        LOG.info("Cannot retrieve process ID of RTS process");
    }

    // Shutdown hooks to clean up at the end of ALL executions (including erroneous termination)
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            LOG.info("SHUTDOWN HOOK : Shutting down process - {}", name);
            executor.shutdownNow();
            if (shutdownThread.getState().equals(Thread.State.NEW)) {
                shutdownThread.start();
                try {
                    shutdownThread.join();
                } catch (InterruptedException e) {
                    process.destroy();
                }
            }
        }
    }));
}

From source file:org.opencastproject.staticfiles.impl.StaticFileServiceImpl.java

/**
 * OSGI callback for activating this component
 *
 * @param cc//from  w ww .j a v  a  2  s  .com
 *          the osgi component context
 */
public void activate(ComponentContext cc) {
    logger.info("Upload Static Resource Service started.");
    registerMXBean = JmxUtil.registerMXBean(staticFileStatistics, "UploadStatistics");
    rootDirPath = OsgiUtil.getContextProperty(cc, STATICFILES_ROOT_DIRECTORY_KEY);

    final File rootFile = new File(rootDirPath);
    if (!rootFile.exists()) {
        try {
            FileUtils.forceMkdir(rootFile);
        } catch (IOException e) {
            throw new ComponentException(
                    String.format("%s does not exists and could not be created", rootFile.getAbsolutePath()));
        }
    }
    if (!rootFile.canRead())
        throw new ComponentException(String.format("Cannot read from %s", rootFile.getAbsolutePath()));

    purgeService = new PurgeTemporaryStorageService();
    purgeService.addListener(new Listener() {
        @Override
        public void failed(State from, Throwable failure) {
            logger.warn("Temporary storage purging service failed: {}", getStackTrace(failure));
        }
    }, MoreExecutors.sameThreadExecutor());
    purgeService.startAsync();
    logger.info("Purging of temporary storage section scheduled");
}

From source file:com.google.idea.blaze.base.experiments.WebExperimentSyncer.java

private void scheduleNextRefresh(boolean refreshWasSuccessful) {
    int delayInMinutes = refreshWasSuccessful ? SUCESSFUL_DOWNLOAD_DELAY_MINUTES
            : DOWNLOAD_FAILURE_DELAY_MINUTES;
    ListenableScheduledFuture<String> refreshResults = executor.schedule(new WebExperimentsDownloader(),
            delayInMinutes, TimeUnit.MINUTES);
    refreshResults.addListener(new WebExperimentsResultProcessor(refreshResults, true),
            MoreExecutors.sameThreadExecutor());
}