All Downloads are FREE. Search and download functionalities are using the official Maven repository.

walkmc.cache.SetCache.kt Maven / Gradle / Ivy

package walkmc.cache

import net.jodah.expiringmap.*
import walkmc.extensions.*
import walkmc.extensions.collections.*
import kotlin.time.*
import java.util.*
import java.util.concurrent.*

/**
 * A specified track used to work with sets. By default the backend [Set] implementation
 * is a [LinkedHashSet]. You can use a backend map to convert from a set.
 */
abstract class SetCache(set: MutableSet = emptyMutableSet()) : MutableSet by set {
	constructor(map: MutableMap) : this(newSetFromMap(map))
	
	/**
	 * Submits a new element to this set registry.
	 */
	fun put(element: E) = add(element)
}

/**
 * A set track implementation that uses [TreeSet] as backend implementation.
 */
open class TreeSetCache(comparator: Comparator? = null) : TreeSet(comparator) {
	constructor(comparator: Comparator?, set: Set) : this(comparator) {
		addAll(set)
	}
	
	constructor(set: Set) : this(null, set)
	constructor(set: SortedSet) : this(set.comparator(), set)
}

/**
 * A set track with a [ExpiringMap] as backend implementation.
 */
open class ExpirableSetCache(
	internal val delegate: ExpiringMap = ExpiringMap.builder().variableExpiration().build(),
) : SetCache(delegate) {
	
	/**
	 * Submits a key-value in this expiring registry with the
	 * specified expiring duration.
	 */
	fun put(
		key: E,
		duration: Long,
		unit: TimeUnit,
		policy: ExpirationPolicy = ExpirationPolicy.CREATED,
	): Boolean? = delegate.put(key, true, policy, duration, unit)
	
	/**
	 * Submits a key-value in this expiring registry with the
	 * specified expiring duration.
	 */
	fun put(key: E, duration: Duration, policy: ExpirationPolicy = ExpirationPolicy.CREATED): Boolean? =
		delegate.put(key, true, policy, duration.inWholeMilliseconds, TimeUnit.MILLISECONDS)
	
	/**
	 * Resets the expiration time of a key.
	 */
	fun reset(key: E) = delegate.resetExpiration(key)
	
	/**
	 * Gets the expirition time of this key.
	 */
	fun expirationOf(key: E): Long = delegate.getExpiration(key)
	
	/**
	 * Gets the expected expirition time of this key.
	 */
	fun expiresIn(key: E): Duration = milliseconds(delegate.getExpectedExpiration(key))
	
	/**
	 * Adds a listener to be triggered when a key expires.
	 * This runs synchronously.
	 */
	fun onExpire(isAsync: Boolean = false, action: (E, Boolean) -> Unit) {
		if (isAsync)
         delegate.addAsyncExpirationListener(action)
		else
         delegate.addExpirationListener(action)
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy