Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Request: new collection, AtomicCache #389

Open
twyatt opened this issue Jul 24, 2024 · 1 comment
Open

Request: new collection, AtomicCache #389

twyatt opened this issue Jul 24, 2024 · 1 comment

Comments

@twyatt
Copy link
Member

twyatt commented Jul 24, 2024

Potential future optimization (not tested):

public class AtomicCacheMap<K, V> private constructor(
    private val atomicMap: AtomicMap<K, V>,
    val maxSize: Int,
) : Map<K, V> by atomicMap {
    public constructor(maxSize: Int) : this(atomicMapOf<K, V>(), maxSize)

    fun clear() {
        atomicMap.mutate { this.clear() }
    }

    fun remove(key: K): V? =
        atomicMap.snapshotAndMutate { remove(key) }.getValue(key)

    fun putAll(from: Map<out K, V>) {
        from.forEach {
            put(it.key, it.value)
        }
    }

    fun put(key: K, value: V): V? =
        atomicMap.mutateAndSnapshot {
            if (this.size >= maxSize) {
                val toRemove = keys.take(maxSize - size + 1)
                    .toSet()
                this.minusAssign(toRemove)
            }
            this.minusAssign(key)
            this[key] = value
        }.getValue(key)
    
    operator fun set(key: K, value: V): V? = put(key, value)
}

Originally posted by @QuantumRand in https://github.com/JuulLabs/conx-sdk/pull/1614#discussion_r1689271840

@cedrickcooke
Copy link
Contributor

It's probably worth spending a bit more time on the data structure. The proposed cache evicts based on insertion order, but an LRU cache seems more generally useful.

@cedrickcooke cedrickcooke changed the title Improvements w/ AtomicMap Request: new collection, AtomicCache Jul 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants