Last active
December 14, 2015 08:48
-
-
Save mgodave/5060406 to your computer and use it in GitHub Desktop.
DelayedFutureTask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.robotninjas.audio; | |
import com.google.common.base.Ticker; | |
import com.google.common.primitives.Longs; | |
import java.util.concurrent.Callable; | |
import java.util.concurrent.Delayed; | |
import java.util.concurrent.FutureTask; | |
import java.util.concurrent.TimeUnit; | |
import static java.util.concurrent.TimeUnit.NANOSECONDS; | |
public class DelayedFutureTask<V> extends FutureTask<V> implements Delayed { | |
private final Ticker ticker; | |
private final long deadline; | |
public DelayedFutureTask(Callable<V> callable, Ticker ticker, long delay, TimeUnit unit) { | |
super(callable); | |
this.ticker = ticker; | |
this.deadline = ticker.read() + NANOSECONDS.convert(delay, unit); | |
} | |
@Override | |
public long getDelay(TimeUnit unit) { | |
final long now = ticker.read(); | |
final long remaining = deadline - now; | |
return unit.convert(remaining, NANOSECONDS); | |
} | |
@Override | |
public int compareTo(Delayed o) { | |
if (o == this) { | |
return 0; | |
} | |
if (o instanceof DelayedFutureTask) { | |
final DelayedFutureTask<?> other = (DelayedFutureTask) o; | |
return Longs.compare(deadline, other.deadline); | |
} | |
return Longs.compare(getDelay(NANOSECONDS), o.getDelay(NANOSECONDS)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment