/** * Simulates some external resource that can only be access by one process at a time */ @Slf4j publicclassFakeLimitedResource{ privatefinal AtomicBoolean inUse = new AtomicBoolean(false);
publicvoiduse(){ // in a real application this would be accessing/manipulating a shared resource
if (!inUse.compareAndSet(false, true)) { thrownew IllegalStateException("Needs to be used by one client at a time"); }
if (waitSeconds <= 0) { lock.acquire(); } elseif (!lock.acquire(waitSeconds, TimeUnit.SECONDS)) { thrownew IllegalStateException("Thread[" + threadName + "] could not acquire the lock"); }
try { log.info("Thread[{}] had the lock", threadName); resource.use(); } finally { log.info("Thread[{}] releasing the lock", threadName); // always release the lock in a finally block lock.release(); } } }