ENT-2414 Named caches (#3848)

* Add named caches and apply to NonInvalidingUnboundCache and all usages.

* Add named caches and apply to NonInvalidingCache and all usages.

* Add named caches and apply to NonInvalidingWeightBasedCache and all usages.

* Move NamedCache to core/internal

* Remove type `NamedCache` and `NamedLoadingCache`

* Suppressed 'name not used' warning, added comment, and fixed generic parameters on the buildNamed functions.

* Use `buildNamed` in all caffeine instances in production code. Not using it for caches that are created in test code.

* Add checks for the cache name

* Formatting

* Minor code review revisions
This commit is contained in:
Christian Sailer
2018-08-24 17:17:22 +01:00
committed by GitHub
parent 042b91814a
commit bc330bd989
29 changed files with 130 additions and 31 deletions

View File

@ -0,0 +1,41 @@
package net.corda.core.internal
import com.github.benmanes.caffeine.cache.Cache
import com.github.benmanes.caffeine.cache.CacheLoader
import com.github.benmanes.caffeine.cache.Caffeine
import com.github.benmanes.caffeine.cache.LoadingCache
/**
* Restrict the allowed characters of a cache name - this ensures that each cache has a name, and that
* the name can be used to create a file name or a metric name.
*/
internal fun checkCacheName(name: String) {
require(!name.isBlank())
require(allowedChars.matches(name))
}
private val allowedChars = Regex("^[0-9A-Za-z_.]*\$")
/* buildNamed is the central helper method to build caffeine caches in Corda.
* This allows to easily add tweaks to all caches built in Corda, and also forces
* cache users to give their cache a (meaningful) name that can be used e.g. for
* capturing cache traces etc.
*
* Currently it is not used in this version of CORDA, but there are plans to do so.
*/
fun <K, V> Caffeine<in K, in V>.buildNamed(name: String): Cache<K, V> {
checkCacheName(name)
return this.build<K, V>()
}
fun <K, V> Caffeine<in K, in V>.buildNamed(name: String, loadFunc: (K) -> V): LoadingCache<K, V> {
checkCacheName(name)
return this.build<K, V>(loadFunc)
}
fun <K, V> Caffeine<in K, in V>.buildNamed(name: String, loader: CacheLoader<K, V>): LoadingCache<K, V> {
checkCacheName(name)
return this.build<K, V>(loader)
}

View File

@ -0,0 +1,24 @@
package net.corda.core.internal
import org.junit.Test
import kotlin.test.assertEquals
class NamedCacheTest {
fun checkNameHelper(name: String, throws: Boolean) {
var exceptionThrown = false
try {
checkCacheName(name)
} catch (e: Exception) {
exceptionThrown = true
}
assertEquals(throws, exceptionThrown)
}
@Test
fun TestCheckCacheName() {
checkNameHelper("abc_123.234", false)
checkNameHelper("", true)
checkNameHelper("abc 123", true)
checkNameHelper("abc/323", true)
}
}