1

原理

利用Executors的Future的限时get方法,Google的SimpleTimeLimiter本质上是对Executors的Future的包装。

实例

package com.facebook.presto.raptor.backup;

import com.facebook.presto.spi.PrestoException;
import com.google.common.util.concurrent.SimpleTimeLimiter;
import com.google.common.util.concurrent.TimeLimiter;
import com.google.common.util.concurrent.UncheckedTimeoutException;
import io.airlift.units.Duration;

import javax.annotation.PreDestroy;

import java.io.File;
import java.util.OptionalLong;
import java.util.UUID;
import java.util.concurrent.ExecutorService;

import static com.facebook.presto.raptor.RaptorErrorCode.RAPTOR_BACKUP_TIMEOUT;
import static io.airlift.concurrent.Threads.daemonThreadsNamed;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

public class TimeoutBackupStore
        implements BackupStore
{
    private final ExecutorService executor;
    private final BackupStore store;

    public TimeoutBackupStore(BackupStore store, String connectorId, Duration timeout)
    {
        requireNonNull(store, "store is null");
        requireNonNull(connectorId, "connectorId is null");
        requireNonNull(timeout, "timeout is null");
        this.executor = newCachedThreadPool(daemonThreadsNamed("backup-proxy-" + connectorId + "-%s"));
        this.store = timeLimited(store, BackupStore.class, timeout, executor);
    }

    @PreDestroy
    public void shutdown()
    {
        executor.shutdownNow();
    }

    @Override
    public void backupShard(UUID uuid, File source)
    {
        try {
            store.backupShard(uuid, source);
        }
        catch (UncheckedTimeoutException e) {
            throw new PrestoException(RAPTOR_BACKUP_TIMEOUT, "Shard backup timed out");
        }
    }

    @Override
    public void restoreShard(UUID uuid, File target)
    {
        try {
            store.restoreShard(uuid, target);
        }
        catch (UncheckedTimeoutException e) {
            throw new PrestoException(RAPTOR_BACKUP_TIMEOUT, "Shard restore timed out");
        }
    }

    @Override
    public OptionalLong shardSize(UUID uuid)
    {
        try {
            return store.shardSize(uuid);
        }
        catch (UncheckedTimeoutException e) {
            throw new PrestoException(RAPTOR_BACKUP_TIMEOUT, "Shard backup size fetch timed out");
        }
    }

    private static <T> T timeLimited(T target, Class<T> clazz, Duration timeout, ExecutorService executor)
    {
        TimeLimiter limiter = new SimpleTimeLimiter(executor);
        return limiter.newProxy(target, clazz, timeout.toMillis(), MILLISECONDS);
    }
}

参考


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...


下一篇 »
akka笔记