Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.eternalcode.core.delay;

/**
* Delay with a predefined default duration, with an option to override per call.
*
* @param <T> key type
*/
public interface DefaultDelay<T> extends ExplicitDelay<T> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rename to FixedDelay. Sounds better imo


/**
* Marks the key using the configured default duration.
*/
void markDelay(T key);
}
Original file line number Diff line number Diff line change
@@ -1,50 +1,61 @@
package com.eternalcode.core.delay;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.time.Duration;
import java.time.Instant;
import java.util.function.Supplier;

public class Delay<T> {

private final Cache<T, Instant> delays;

private final Supplier<Duration> delaySettings;

public Delay(Supplier<Duration> delayProvider) {
this.delaySettings = delayProvider;

this.delays = CacheBuilder.newBuilder()
.expireAfterWrite(delayProvider.get())
.build();
/**
* Factory class for creating delay instances.
* <p>
* Naming convention:
* - withDefault(...) -> DefaultDelay (uses predefined Duration)
* - explicit(...) -> ExplicitDelay (requires explicit Duration each time)
*/
public final class Delay {

private Delay() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
}

public void markDelay(T key, Duration delay) {
this.delays.put(key, Instant.now().plus(delay));
/**
* Creates a DefaultDelay with the default cache size.
*
* @param defaultDelay the default duration used for delays
* @param <T> the key type
* @return DefaultDelay instance
*/
public static <T> DefaultDelay<T> withDefault(Duration defaultDelay) {
return new GuavaDefaultDelay<>(defaultDelay);
}

public void markDelay(T key) {
this.markDelay(key, this.delaySettings.get());
/**
* Creates a DefaultDelay with a custom maximum cache size.
*
* @param defaultDelay the default duration used for delays
* @param maximumSize maximum number of entries in the cache
* @param <T> the key type
* @return DefaultDelay instance
*/
public static <T> DefaultDelay<T> withDefault(Duration defaultDelay, long maximumSize) {
return new GuavaDefaultDelay<>(defaultDelay, maximumSize);
}

public void unmarkDelay(T key) {
this.delays.invalidate(key);
/**
* Creates an ExplicitDelay with the default cache size.
*
* @param <T> the key type
* @return ExplicitDelay instance
*/
public static <T> ExplicitDelay<T> explicit() {
return new GuavaExplicitDelay<>();
}

public boolean hasDelay(T key) {
Instant delayExpireMoment = this.getDelayExpireMoment(key);

return Instant.now().isBefore(delayExpireMoment);
/**
* Creates an ExplicitDelay with a custom maximum cache size.
*
* @param maximumSize maximum number of entries in the cache
* @param <T> the key type
* @return ExplicitDelay instance
*/
public static <T> ExplicitDelay<T> explicit(long maximumSize) {
return new GuavaExplicitDelay<>(maximumSize);
}

public Duration getDurationToExpire(T key) {
return Duration.between(Instant.now(), this.getDelayExpireMoment(key));
}

private Instant getDelayExpireMoment(T key) {
return this.delays.asMap().getOrDefault(key, Instant.MIN);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.eternalcode.core.delay;

import java.time.Duration;
import java.time.Instant;

/**
* Common delay operations shared by all delay types.
*
* @param <T> key type
*/
interface DelayActions<T> {

/**
* Removes any existing delay for the key.
* */
void unmarkDelay(T key);

/**
* @return true, if the key has an active delay; expired entries are cleaned on read.
*/
boolean hasDelay(T key);

/**
* @return remaining duration or {@code Duration.ZERO} if none/expired.
*/
Duration getRemaining(T key);

/**
* @return expiration instant or {@code null} if none/expired.
*/
Instant getExpireAt(T key);

/**
* Extends current delay by {@code extra}; if none/expired, starts now.
* Non-positive durations are ignored.
*/
void extendDelay(T key, Duration extra);
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.eternalcode.core.delay;

import java.time.Duration;

/**
* Delay that requires an explicit duration on marking.
*
* @param <T> key type
*/
public interface ExplicitDelay<T> extends DelayActions<T> {

/**
* Marks the key with the given duration.
* Non-positive durations remove the entry.
*/
void markDelay(T key, Duration duration);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.eternalcode.core.delay;

import java.time.Duration;

/**
* {@link DefaultDelay} implementation backed by {@link GuavaDelay}.
* <p>
* Stores a per-entry expiration instant in the cache. Unlike using
* {@code expireAfterWrite}, each entry is managed individually by its
* {@link java.time.Instant}.
* <p>
* Calling {@link #markDelay(Object)} uses the predefined {@link #defaultDelay}.
*
* @param <T> the type of key used to identify delays
*/
final class GuavaDefaultDelay<T> extends GuavaDelay<T> implements DefaultDelay<T> {

private final Duration defaultDelay;

/**
* Creates a new delay manager with the given default delay and
* the default maximum cache size.
*
* @param defaultDelay the default duration applied when marking a key,
* must be positive
*/
GuavaDefaultDelay(Duration defaultDelay) {
this(defaultDelay, DEFAULT_MAXIMUM_SIZE);
}

/**
* Creates a new delay manager with the given default delay and a
* custom maximum cache size.
*
* @param defaultDelay the default duration applied when marking a key,
* must be positive
* @param maximumSize maximum number of entries allowed in the cache
*/
GuavaDefaultDelay(Duration defaultDelay, long maximumSize) {
super(maximumSize);
this.defaultDelay = defaultDelay;
}

/**
* Marks the specified key with the configured {@link #defaultDelay}.
*
* @param key the key to mark
*/
@Override
public void markDelay(T key) {
putDelay(key, this.defaultDelay);
}

@Override
public void markDelay(T key, Duration duration) {
putDelay(key, duration);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
package com.eternalcode.core.delay;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.time.Duration;
import java.time.Instant;

/**
* Base class providing shared logic for delay implementations using a Guava cache.
* <p>
* Each key is associated with an {@link Instant} representing the expiration time.
* Expired entries are cleaned up eagerly on read operations.
* <p>
* Contract:
* <ul>
* <li>{@link #getRemaining(Object)} returns {@code Duration.ZERO} if no active delay exists.</li>
* <li>{@link #getExpireAt(Object)} returns {@code null} if no active delay exists.</li>
* <li>Durations &lt;= 0 in {@code putDelay} or {@code extendDelay} are treated as no delay (entry is removed).</li>
* </ul>
* <p>
* Thread-safe as guaranteed by Guava's {@link Cache}.
*
* @param <T> the type of key used to identify delays
*/
abstract class GuavaDelay<T> {

/** Default maximum number of cache entries. */
protected static final long DEFAULT_MAXIMUM_SIZE = 50_000L;

/** Underlying Guava cache mapping keys to expiration instants. */
protected final Cache<T, Instant> cache;

/**
* Creates a new GuavaDelay with a custom maximum cache size.
*
* @param maximumSize the maximum number of entries in the cache
*/
protected GuavaDelay(long maximumSize) {
this.cache = CacheBuilder.newBuilder()
.maximumSize(maximumSize)
.build();
}

/**
* Stores a delay until the given expiration instant.
*
* @param key the key to mark
* @param expireAt the expiration instant
*/
protected void putDelay(T key, Instant expireAt) {
this.cache.put(key, expireAt);
}

/**
* Stores a delay for the given duration starting from now.
* Durations &lt;= 0 are treated as no delay and will remove the entry.
*
* @param key the key to mark
* @param duration the delay duration
*/
protected void putDelay(T key, Duration duration) {
if (duration.isZero() || duration.isNegative()) {
this.cache.invalidate(key);
return;
}

this.cache.put(key, Instant.now().plus(duration));
}

/**
* Removes any existing delay for the given key.
*
* @param key the key to unmark
*/
public void unmarkDelay(T key) {
this.cache.invalidate(key);
}

/**
* Checks if the given key currently has an active delay.
* Expired entries are removed on read.
*
* @param key the key to check
* @return true if an active delay exists, false otherwise
*/
public boolean hasDelay(T key) {
Instant until = this.cache.getIfPresent(key);
if (until == null) {
return false;
}

if (!Instant.now().isBefore(until)) {
this.cache.invalidate(key);
return false;
}

return true;
}

/**
* Returns the remaining duration of the delay for the given key.
* Returns {@code Duration.ZERO} if no active delay exists.
*
* @param key the key to check
* @return remaining duration, or {@code Duration.ZERO} if none
*/
public Duration getRemaining(T key) {
Instant until = this.cache.getIfPresent(key);
if (until == null) {
return Duration.ZERO;
}

Duration left = Duration.between(Instant.now(), until);
if (left.isNegative() || left.isZero()) {
this.cache.invalidate(key);
return Duration.ZERO;
}

return left;
}

/**
* Returns the expiration instant of the delay for the given key.
* Returns {@code null} if no active delay exists.
*
* @param key the key to check
* @return expiration instant, or {@code null} if none
*/
public Instant getExpireAt(T key) {
Instant until = this.cache.getIfPresent(key);
if (until == null) {
return null;
}

if (Instant.now().isAfter(until)) {
this.cache.invalidate(key);
return null;
}

return until;
}

/**
* Extends the delay for the given key by the specified duration.
* If no active delay exists, a new one is created starting now.
* Durations &lt;= 0 are ignored.
*
* @param key the key to extend
* @param extra the duration to add
*/
public void extendDelay(T key, Duration extra) {
if (extra.isZero() || extra.isNegative()) {
return;
}

Instant base = this.cache.getIfPresent(key);
Instant now = Instant.now();
Instant start = (base == null || !now.isBefore(base)) ? now : base;
this.cache.put(key, start.plus(extra));
}
}
Loading