package org.example.demo;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class AutoLock {
private final String lock;
private static final Map<String, ScheduledExecutorService> lockList = new HashMap<>();
private AutoLock(String lock, Integer timeout) {
this.lock = lock;
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
lockList.put(lock, scheduler);
scheduler.schedule(this::unlock, timeout, TimeUnit.SECONDS);
}
private synchronized void unlock() {
lockList.remove(lock);
}
public static synchronized boolean tryLockTask(String lock) {
return lockList.get(lock) == null;
}
public static synchronized void createLockTask(String lock, Integer timeout) {
new AutoLock(lock, timeout);
}
public static synchronized void createLockTask(String lock) {
createLockTask(lock, 5);
}
public static synchronized void unLockTask(String lock) {
lockList.get(lock).shutdown();
lockList.remove(lock);
}
}