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

org.jetbrains.kotlin.analysis.utils.caches.SoftCachedMap.kt Maven / Gradle / Ivy

There is a newer version: 2.1.0-Beta1
Show newest version
/*
 * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
 * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
 */

package org.jetbrains.kotlin.analysis.utils.caches

import com.intellij.openapi.project.Project
import com.intellij.psi.util.CachedValue
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.util.CachedValueBase
import com.intellij.util.containers.ContainerUtil
import java.util.concurrent.ConcurrentHashMap

public abstract class SoftCachedMap {
    public abstract fun getOrPut(key: K, create: () -> V): V

    public abstract fun clear()

    public abstract fun clearCachedValues()

    public companion object {
        public fun  create(
            project: Project,
            kind: Kind,
            trackers: List
        ): SoftCachedMap = when {
            trackers.isEmpty() -> SoftCachedMapWithoutTrackers(kind)
            else -> SoftCachedMapWithTrackers(project, kind, trackers.toTypedArray())
        }
    }

    public enum class Kind {
        SOFT_KEYS_SOFT_VALUES,
        STRONG_KEYS_SOFT_VALUES
    }
}

private class SoftCachedMapWithTrackers(
    private val project: Project,
    kind: Kind,
    private val trackers: Array
) : SoftCachedMap() {
    private val cache = when (kind) {
        Kind.SOFT_KEYS_SOFT_VALUES -> ContainerUtil.createConcurrentSoftMap>()
        Kind.STRONG_KEYS_SOFT_VALUES -> ConcurrentHashMap>()
    }

    override fun clear() {
        cache.clear()
    }

    override fun clearCachedValues() {
        cache.values.forEach {
            (it as? CachedValueBase<*>)?.clear()
        }
    }

    override fun getOrPut(key: K, create: () -> V): V {
        return cache.getOrPut(key) {
            CachedValuesManager.getManager(project).createCachedValue {
                CachedValueProvider.Result(create(), *trackers)
            }
        }.value
    }
}

private class SoftCachedMapWithoutTrackers(kind: Kind) : SoftCachedMap() {
    private val cache = when (kind) {
        Kind.SOFT_KEYS_SOFT_VALUES -> ContainerUtil.createConcurrentSoftKeySoftValueMap()
        Kind.STRONG_KEYS_SOFT_VALUES -> ContainerUtil.createSoftValueMap()
    }

    override fun clear() {
        cache.clear()
    }

    override fun clearCachedValues() {}

    override fun getOrPut(key: K, create: () -> V): V {
        return cache.getOrPut(key, create)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy