main

square/leakcanary

Last updated at: 29/12/2023 09:38

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 type T is used to cast and return the value, or null 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. The defaultValue 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
  }
}