package com.android.commands.monkey.ape.jev;

/** Caller-owned monotonic budget. Does not claim to preempt JVM/GUI operations. */
final class JevDeadline implements AutoCloseable {
    static final class Expired extends RuntimeException { private static final long serialVersionUID=1L; }
    private static final ThreadLocal<Long> deadline=new ThreadLocal<Long>();
    private final Long prior;
    private JevDeadline(long absolute){prior=deadline.get();deadline.set(absolute);}
    static JevDeadline enter(long absolute){return new JevDeadline(absolute);}
    static long absolute(){Long value=deadline.get();return value==null?Long.MAX_VALUE:value;}
    static void check(){if(System.nanoTime()>=absolute() || Thread.currentThread().isInterrupted())throw new Expired();}
    static void lock(java.util.concurrent.locks.ReentrantLock lock) {
        if(absolute()==Long.MAX_VALUE){lock.lock();return;}
        try{if(!lock.tryLock(Math.max(0,absolute()-System.nanoTime()),java.util.concurrent.TimeUnit.NANOSECONDS))throw new Expired();}
        catch(InterruptedException e){Thread.currentThread().interrupt();throw new Expired();}
    }
    public void close(){if(prior==null)deadline.remove();else deadline.set(prior);}
}
