JobContext.kt
TLDR
The provided file, JobContext.kt
, implements a simple in-memory store for storing objects in a HeapAnalysisJob
instance. It is a MutableMap
of type <String, Any>
, with backward compatibility for handling unsafe generics access. The JobContext
class provides methods for accessing, adding, and removing items from the store.
Classes
JobContext
The JobContext
class represents an in-memory store that can be used to store objects in a HeapAnalysisJob
instance. It holds a starter
class that triggered the start of the job.
Methods
-
get(key: String): T?
: Retrieves the value associated with the specified key from the store. The generic typeT
is used to cast and return the value, ornull
if the key does not exist. -
getOrPut(key: String, defaultValue: () -> T): T
: Retrieves the value associated with the specified key from the store, or inserts and returns a default value if the key does not exist. ThedefaultValue
is a lambda function that provides the default value to store. -
set(key: String, value: T)
: Sets the value associated with the specified key in the store. -
contains(key: String): Boolean
: Checks if the store contains the specified key. -
minusAssign(key: String)
: Removes the value associated with the specified key from the store.
package leakcanary
import java.util.concurrent.ConcurrentHashMap
import kotlin.reflect.KClass
/**
* In memory store that can be used to store objects in a given [HeapAnalysisJob] instance.
* This is a simple [MutableMap] of [String] to [Any], but with unsafe generics access.
*
* By convention, [starter] should be the class that triggered the start of the job.
*/
class JobContext constructor(val starter: Class<*>? = null) {
constructor(starter: KClass<*>) : this(starter.java)
private val store = ConcurrentHashMap<String, Any?>()
operator fun <T> get(key: String): T? {
@Suppress("UNCHECKED_CAST")
return store[key] as T?
}
/**
* @see MutableMap.getOrPut
*/
fun <T> getOrPut(
key: String,
defaultValue: () -> T
): T {
@Suppress("UNCHECKED_CAST")
return store.getOrPut(key) {
defaultValue()
} as T
}
/**
* @see MutableMap.set
*/
operator fun <T> set(
key: String,
value: T
) {
store[key] = (value as Any?)
}
/**
* @see MutableMap.containsKey
*/
operator fun contains(key: String): Boolean {
return store.containsKey(key)
}
/**
* @see MutableMap.remove
*/
operator fun minusAssign(key: String) {
@Suppress("UNCHECKED_CAST")
store -= key
}
}