gpt4 book ai didi

java - 等待 0 延迟的预定 future 的最佳方式是什么?

转载 作者:行者123 更新时间:2023-12-02 12:03:22 25 4
gpt4 key购买 nike

我试图避免让当前线程 hibernate ,直到 ScheduledFuture 以 0 延迟执行。不幸的是,我找不到一个针对 future 的钩子(Hook)来通知可运行对象何时执行。所讨论的 future 包装了 guava cache.put(key,value) 操作。应在缓存使 key 过期之前调用可运行对象...本质上,我希望一个 key 永不过期。

    final Runnable refresh = new Runnable() {
@Override
public void run()
{
cache.put( key, value );
}
};

// replace the token when 95% of the ttl has passed
long refreshInterval = (long)( keyExpires * 1000 *
0.5 );

// execute the future task and then delay the current thread long enough for the
// executor to process the runnable. 50 ms should be long enough.
ScheduledFuture<?> future = scheduler.scheduleAtFixedRate( refresh,
0,
refreshInterval,
TimeUnit.MILLISECONDS );

/// this is the code I'd like to avoid
try {
Thread.sleep( 50 );
} catch( InterruptedException e1 ) {} catch( ExecutionException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}

执行器服务确实会立即运行代码,但启动线程有延迟时间。该延迟将是系统特定的,因此我想避免任意 sleep 。

我正在使用 ScheduledThreadPoolExecutor 创建 ScheduledFuture,并且我可以使用该类型的访问器(例如 isDone())获得我想要的行为。然而,这似乎也很古怪。是否有一个更干净的实现,可以提供 hibernate 当前线程的行为,而不使用 Executor 服务的副作用?

谢谢,罗宾

编辑:显示没有 Thread.sleep() 时失败的测试

    cache.putNonExpiring( "key", "value" );
Assert.assertNotNull( "Immediate get should have value", cache.get( "key" ) );

要正常工作,应同步执行 put(key,value) 以允许立即执行 get(key) 操作。

最佳答案

也许您可以使用当前线程阻塞的信​​号量或其他同步类型,直到刷新可运行对象释放信号量

// A semaphore initialized with no permits
final Semaphore runnableExecuting = new Sempahore(0);

final Runnable refresh = new Runnable()
{
@Override
public void run()
{
// Release one permit. This should unblock the thread
// scheduled this task. After the initial releasing
// the semaphore is essentially unneeded
runnableExecuting.release();

// Your code
}
}

// After executor scheduling

// Attempt to acquire a permit, which the semphore initially has none.
// This will block until a permit becomes available
runnableExecuting.acquire();

关于java - 等待 0 延迟的预定 future 的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47079917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com