// Created on savesnippets.com · https://savesnippets.com/BcgNzoHrmGX3yt import java.util.concurrent.locks.*; import java.util.concurrent.*; class Demo { private final ReentrantLock lock = new ReentrantLock(); private int balance = 100; boolean withdraw(int amount) { lock.lock(); // blocks if held try { if (balance < amount) return false; balance -= amount; return true; } finally { lock.unlock(); // ALWAYS unlock in finally } } // tryLock with timeout — bail out rather than block forever boolean tryWithdraw(int amount, long ms) throws InterruptedException { if (!lock.tryLock(ms, TimeUnit.MILLISECONDS)) return false; try { if (balance < amount) return false; balance -= amount; return true; } finally { lock.unlock(); } } }