MemorySnapshot


public final class MemorySnapshot


A lightweight, point-in-time snapshot of memory metrics for processes in an application.

MemorySnapshot provides low-overhead memory statistics designed for routine telemetry, performance monitoring, and regression tracking. Unlike heavyweight diagnostic tools such as android.os.Debug.getMemoryInfo or android.app.ActivityManager.getProcessMemoryInfo, capturing a MemorySnapshot is optimized for minimal overhead, making it practical for periodic sampling and in-app health diagnostics without incurring expensive system traversals or platform rate-limiting.

An instance is created by calling MemorySnapshot.capture. All memory quantities are reported in bytes. If an individual metric is not available on the current device, its property returns -1L.

Thread Safety

MemorySnapshot instances are immutable and thread-safe. MemorySnapshot.capture is thread-safe and can be called concurrently from any thread.

val snapshot = MemorySnapshot.capture() ?: return

// Resident memory metrics (in bytes)
val rssBytes = snapshot.rssBytes
val anonRssBytes = snapshot.anonRssBytes
val fileRssBytes = snapshot.fileRssBytes
val shmemRssBytes = snapshot.shmemRssBytes
val peakRssBytes = snapshot.rssHwmBytes

// Example: calculate total resident memory from resident memory of files, anonymous and shmem
if (fileRssBytes >= 0 && anonRssBytes >= 0 && shmemRssBytes >= 0) {
    val sumRssBytes = anonRssBytes + fileRssBytes + shmemRssBytes
    // sumRssBytes should be equal (or close) to rssBytes
}

// Total virtual memory including swap (in bytes)
val vssBytes = snapshot.vssBytes

// Anonymous memory on swap (in bytes)
val swapBytes = snapshot.swapBytes

// Example: calculate total anonymous memory including swap
if (anonRssBytes >= 0 && swapBytes >= 0) {
    val totalAnonBytes = anonRssBytes + swapBytes
}

// Cgroup memory usage (in bytes)
val processCgroupBytes = snapshot.processMemoryUsageBytes
val packageCgroupBytes = snapshot.packageMemoryUsageBytes

// Example: Convert to megabytes and log or record metrics of resident anonymous memory
val anonRssMb = if (anonRssBytes >= 0) anonRssBytes / (1024 * 1024) else -1
recordAppMemoryMetric(anonRssMb)
// Capture snapshot for the target process. Returns null if capture fails (e.g., if the
// target process has already terminated).
val snapshot = MemorySnapshot.capture(pid) ?: return

// Resident memory metrics for the target process (in bytes)
val rssBytes = snapshot.rssBytes
val anonRssBytes = snapshot.anonRssBytes
val fileRssBytes = snapshot.fileRssBytes
val shmemRssBytes = snapshot.shmemRssBytes
val swapBytes = snapshot.swapBytes

// Total anonymous memory including swap for the secondary process
if (anonRssBytes >= 0 && swapBytes >= 0) {
    val totalAnonBytes = anonRssBytes + swapBytes
    recordProcessMemory(pid, totalAnonBytes)
}

// Process-specific cgroup memory usage (in bytes)
val processCgroupBytes = snapshot.processMemoryUsageBytes
// Package-wide cgroup memory usage across all processes under this UID (in bytes)
val packageCgroupBytes = snapshot.packageMemoryUsageBytes

// When both process and package cgroup metrics are available (Android 17+),
// calculate this process's contribution to total application memory footprint
if (processCgroupBytes >= 0 && packageCgroupBytes > 0) {
    val memoryShare = (processCgroupBytes * 100.0) / packageCgroupBytes
    recordProcessMemoryShare(pid, memoryShare)
}
val before = MemorySnapshot.capture()

performMemoryIntensiveOperation()

val after = MemorySnapshot.capture()

// On Android devices with zRAM enabled, memory pressure during an intensive
// operation can cause the system to compress anonymous memory into swap.
// Evaluating `after.anonRssBytes - before.anonRssBytes` alone can
// underestimate the memory growth if anonymous pages were swapped out
// during the operation. A better way is to combine both anonRssBytes and
// swapBytes to evaluate the increase of anonymous memory usage.
//
// NOTE: the difference could be negative if GC happened during the operation,
// which means more memory was released than allocated
if (before != null && after != null) {
    // Track the difference in total anonymous memory
    if (
        before.anonRssBytes >= 0 &&
            after.anonRssBytes >= 0 &&
            before.swapBytes >= 0 &&
            after.swapBytes >= 0
    ) {
        val anonDeltaBytes =
            (after.anonRssBytes + after.swapBytes) - (before.anonRssBytes + before.swapBytes)
        recordMemoryDelta(anonDeltaBytes)
    }
}
See also
capture

Summary

Public methods

static final MemorySnapshot

Captures a point-in-time MemorySnapshot for the current process.

static final MemorySnapshot
capture(int pid)

Captures a point-in-time MemorySnapshot for the specified process id.

final long

Anonymous Resident Set Size in bytes, or -1L if unavailable.

final long

File-backed Resident Set Size in bytes, or -1L if unavailable.

final long

Package-wide (UID cgroup) memory usage in bytes, or -1L if unavailable.

final long

Process-specific cgroup memory usage in bytes, or -1L if unavailable.

final long

Total Resident Set Size (RSS) in bytes, or -1L if unavailable.

final long

Resident Set Size High-Water Mark (RSS HWM) in bytes, or -1L if unavailable.

final long

Shared memory Resident Set Size in bytes, or -1L if unavailable.

final long

Total swap memory used by the process in bytes, or -1L if unavailable.

final long

Virtual Set Size (VSS) in bytes, or -1L if unavailable.

Public methods

capture

public static final MemorySnapshot capture()

Captures a point-in-time MemorySnapshot for the current process.

This method parses /proc/self/status and reads process-specific and package-wide cgroup memory counters when accessible. The operation is designed to be low-latency, memory-efficient and threadsafe (can be called concurrently from any thread).

Returns
MemorySnapshot

an immutable MemorySnapshot instance reflecting current memory state, or null if the kernel memory stats cannot be read or both VmRSS and VmSize are unavailable. A null return value here indicates a persistent error and subsequent calling of this method is not recommended.

capture

public static final MemorySnapshot capture(int pid)

Captures a point-in-time MemorySnapshot for the specified process id. The target process must belong to the calling application.

Note: When the target process is not the calling process, vssBytes may not be available, and its value in the returned MemorySnapshot may be -1L.

// Capture snapshot for the target process. Returns null if capture fails (e.g., if the
// target process has already terminated).
val snapshot = MemorySnapshot.capture(pid) ?: return

// Resident memory metrics for the target process (in bytes)
val rssBytes = snapshot.rssBytes
val anonRssBytes = snapshot.anonRssBytes
val fileRssBytes = snapshot.fileRssBytes
val shmemRssBytes = snapshot.shmemRssBytes
val swapBytes = snapshot.swapBytes

// Total anonymous memory including swap for the secondary process
if (anonRssBytes >= 0 && swapBytes >= 0) {
    val totalAnonBytes = anonRssBytes + swapBytes
    recordProcessMemory(pid, totalAnonBytes)
}

// Process-specific cgroup memory usage (in bytes)
val processCgroupBytes = snapshot.processMemoryUsageBytes
// Package-wide cgroup memory usage across all processes under this UID (in bytes)
val packageCgroupBytes = snapshot.packageMemoryUsageBytes

// When both process and package cgroup metrics are available (Android 17+),
// calculate this process's contribution to total application memory footprint
if (processCgroupBytes >= 0 && packageCgroupBytes > 0) {
    val memoryShare = (processCgroupBytes * 100.0) / packageCgroupBytes
    recordProcessMemoryShare(pid, memoryShare)
}
Parameters
int pid

the process ID to capture, or 0 for the calling process.

Returns
MemorySnapshot

an immutable MemorySnapshot instance reflecting current memory state, or null if capture fails (for example, if the target process has already terminated or kernel memory statistics cannot be read).

Throws
IllegalArgumentException

if pid is negative or does not belong to the calling application.

getAnonRssBytes

public final long getAnonRssBytes()

Anonymous Resident Set Size in bytes, or -1L if unavailable.

Represents the portion of physical RAM allocated to memory not backed by a file, such as the Java heap, native heap (malloc/mmap), and thread stacks. This is typically the most critical metric for tracking heap allocation growth and diagnosing memory leaks.

Corresponds to RssAnon in /proc/self/status.

NOTE: on Android devices with swap/zRAM enabled, anonymous memory under pressure may be paged to swap, evaluating total anonymous memory footprint requires combining anonRssBytes with swapBytes.

getFileRssBytes

public final long getFileRssBytes()

File-backed Resident Set Size in bytes, or -1L if unavailable.

Represents the memory mapped to files on disk, such as DEX bytecode, native shared libraries (.so), assets, and resource caches. Clean file-backed pages can be reclaimed by the system under memory pressure without requiring swap space. Corresponds to RssFile in /proc/self/status.

getPackageMemoryUsageBytes

public final long getPackageMemoryUsageBytes()

Package-wide (UID cgroup) memory usage in bytes, or -1L if unavailable.

Represents the aggregate memory usage across all processes running under the application's UID, as accounted by memory controller (memory.current in the UID cgroup).

NOTE: This gives multi-process apps their combined memory usage without inter-process queries.

getProcessMemoryUsageBytes

public final long getProcessMemoryUsageBytes()

Process-specific cgroup memory usage in bytes, or -1L if unavailable.

Represents memory usage attributed directly to the process by the memory controller (memory.current in the process cgroup).

NOTE: processMemoryUsageBytes and packageMemoryUsageBytes requires Android 17 or higher, and will return -1L otherwise (on devices where system memory accounting is unavailable).

getRssBytes

public final long getRssBytes()

Total Resident Set Size (RSS) in bytes, or -1L if unavailable.

Represents the total amount of physical RAM currently occupied by the target process, including anonymous allocations, memory-mapped files, and shared memory mappings. This is equal to the sum of anonRssBytes, fileRssBytes and shmemRssBytes.

Corresponds to VmRSS in /proc/self/status.

getRssHwmBytes

public final long getRssHwmBytes()

Resident Set Size High-Water Mark (RSS HWM) in bytes, or -1L if unavailable.

Represents the peak physical RAM usage (maximum RSS) reached by the process during its lifetime up to the snapshot. Useful for tracking peak memory consumption across workflows. Corresponds to VmHWM in /proc/self/status.

NOTE: This is cumulative over the lifetime of the process and does NOT reset between snapshots.

getShmemRssBytes

public final long getShmemRssBytes()

Shared memory Resident Set Size in bytes, or -1L if unavailable.

Represents the memory occupied by shared memory mappings. This includes memfd/ashmem, inter-process shared memory (rather than regular shared file mappings, which are accounted under file RSS). Corresponds to RssShmem in /proc/self/status.

getSwapBytes

public final long getSwapBytes()

Total swap memory used by the process in bytes, or -1L if unavailable.

Represents the amount of anonymous memory paged out into swap or compressed RAM (such as zRAM). Corresponds to VmSwap in /proc/self/status.

getVssBytes

public final long getVssBytes()

Virtual Set Size (VSS) in bytes, or -1L if unavailable.

Represents the total virtual address space mapped by the process. This includes memory residing in physical RAM, memory swapped out, as well as memory that is reserved but with no physical pages allocated. Corresponds to VmSize in /proc/self/status.

NOTE: This does NOT reflect the physical memory consumed, and is NOT indicative of memory leaks or OOM risks.