import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.Objects; public class FloodProtectedMethod { private LocalDateTime shallExecutedAfter = null; private ChronoUnit chronoUnit; private long delay; public FloodProtectedMethod(ChronoUnit chronoUnit, long delay) { this.chronoUnit = chronoUnit; this.delay = delay; } public boolean inject(Runnable runnable) { LocalDateTime now = LocalDateTime.now(); synchronized(this) { if (Objects.isNull(shallExecutedAfter) || shallExecutedAfter.isBefore(now)) { shallExecutedAfter = now.plus(delay, chronoUnit); runnable.run(); return true; } } return false; } }