@UnstableApi
public final class SimpleCache implements Cache


A Cache implementation that maintains an in-memory representation.

Only one instance of SimpleCache is allowed for a given directory at a given time.

To delete a SimpleCache, use delete rather than deleting the directory and its contents directly. This is necessary to ensure that associated index data is also removed.

Summary

Public fields

long

Public constructors

SimpleCache(File cacheDir, CacheEvictor evictor)

This method is deprecated.

Use a constructor that takes a DatabaseProvider for improved performance.

SimpleCache(
    File cacheDir,
    CacheEvictor evictor,
    DatabaseProvider databaseProvider
)

Constructs the cache.

SimpleCache(
    File cacheDir,
    CacheEvictor evictor,
    @Nullable DatabaseProvider databaseProvider,
    @Nullable byte[] legacyIndexSecretKey,
    boolean legacyIndexEncrypt,
    boolean preferLegacyIndex
)

Constructs the cache.

Public methods

synchronized NavigableSet<CacheSpan>

Registers a listener to listen for changes to a given resource.

synchronized void

Applies mutations to the ContentMetadata for the given resource.

synchronized void

Checks whether the cache was initialized successfully.

synchronized void
commitFile(File file, long length)

Commits a file into the cache.

static void
@WorkerThread
delete(File cacheDir, @Nullable DatabaseProvider databaseProvider)

Deletes all content belonging to a cache instance.

synchronized long

Returns the total disk space in bytes used by the cache.

synchronized long
getCachedBytes(String key, long position, long length)

Returns the total number of cached bytes between position (inclusive) and (position + length) (exclusive) of a resource.

synchronized long
getCachedLength(String key, long position, long length)

Returns the length of continuously cached data starting from position, up to a maximum of maxLength, of a resource.

synchronized NavigableSet<CacheSpan>

Returns the cached spans for a given resource.

synchronized ContentMetadata

Returns a ContentMetadata for the given resource.

synchronized Set<String>

Returns the cache keys of all of the resources that are at least partially cached.

synchronized long

Returns a non-negative unique identifier for the cache, or UID_UNSET if initialization failed before the unique identifier was determined.

synchronized static boolean

Returns whether cacheFolder is locked by a SimpleCache instance.

synchronized boolean
isCached(String key, long position, long length)

Returns whether the specified range of data in a resource is fully cached.

synchronized void

Releases the cache.

synchronized void

Releases a CacheSpan obtained from startReadWrite which corresponded to a hole in the cache.

synchronized void

Unregisters a listener.

synchronized void

Removes all CacheSpans for a resource, deleting the underlying files.

synchronized void

Removes a cached CacheSpan from the cache, deleting the underlying file.

synchronized File
startFile(String key, long position, long length)

Obtains a cache file into which data can be written.

synchronized CacheSpan
startReadWrite(String key, long position, long length)

A caller should invoke this method when they require data starting from a given position in a given resource.

synchronized @Nullable CacheSpan
startReadWriteNonBlocking(String key, long position, long length)

Same as startReadWrite.

Inherited Constants

From androidx.media3.datasource.cache.Cache
static final long

Returned by getUid if initialization failed before the unique identifier was read or generated.

Public fields

uid

public long uid

Public constructors

SimpleCache

public SimpleCache(File cacheDir, CacheEvictor evictor)

Constructs the cache. The cache will delete any unrecognized files from the directory. Hence the directory cannot be used to store other files.

Parameters
File cacheDir

A dedicated cache directory.

CacheEvictor evictor

The evictor to be used. For download use cases where cache eviction should not occur, use NoOpCacheEvictor.

SimpleCache

public SimpleCache(
    File cacheDir,
    CacheEvictor evictor,
    DatabaseProvider databaseProvider
)

Constructs the cache. The cache will delete any unrecognized files from the directory. Hence the directory cannot be used to store other files.

Parameters
File cacheDir

A dedicated cache directory.

CacheEvictor evictor

The evictor to be used. For download use cases where cache eviction should not occur, use NoOpCacheEvictor.

DatabaseProvider databaseProvider

Provides the database in which the cache index is stored.

SimpleCache

public SimpleCache(
    File cacheDir,
    CacheEvictor evictor,
    @Nullable DatabaseProvider databaseProvider,
    @Nullable byte[] legacyIndexSecretKey,
    boolean legacyIndexEncrypt,
    boolean preferLegacyIndex
)

Constructs the cache. The cache will delete any unrecognized files from the cache directory. Hence the directory cannot be used to store other files.

Parameters
File cacheDir

A dedicated cache directory.

CacheEvictor evictor

The evictor to be used. For download use cases where cache eviction should not occur, use NoOpCacheEvictor.

@Nullable DatabaseProvider databaseProvider

Provides the database in which the cache index is stored, or null to use a legacy index. Using a database index is highly recommended for performance reasons.

@Nullable byte[] legacyIndexSecretKey

A 16 byte AES key for reading, and optionally writing, the legacy index. Not used by the database index, however should still be provided when using the database index in cases where upgrading from the legacy index may be necessary.

boolean legacyIndexEncrypt

Whether to encrypt when writing to the legacy index. Must be false if legacyIndexSecretKey is null. Not used by the database index.

boolean preferLegacyIndex

Whether to use the legacy index even if a databaseProvider is provided. Should be false in nearly all cases. Setting this to true is only useful for downgrading from the database index back to the legacy index.

Public methods

addListener

synchronized public NavigableSet<CacheSpanaddListener(String key, Cache.Listener listener)

Registers a listener to listen for changes to a given resource.

No guarantees are made about the thread or threads on which the listener is called, but it is guaranteed that listener methods will be called in a serial fashion (i.e. one at a time) and in the same order as events occurred.

Parameters
String key

The cache key of the resource.

Cache.Listener listener

The listener to add.

Returns
NavigableSet<CacheSpan>

The current spans for the resource.

applyContentMetadataMutations

synchronized public void applyContentMetadataMutations(
    String key,
    ContentMetadataMutations mutations
)

Applies mutations to the ContentMetadata for the given resource. A new is added if there isn't one already for the resource.

This method may be slow and shouldn't normally be called on the main thread.

Parameters
String key

The cache key of the resource.

ContentMetadataMutations mutations

Contains mutations to be applied to the metadata.

Throws
androidx.media3.datasource.cache.Cache.CacheException

If an error is encountered.

checkInitialization

synchronized public void checkInitialization()

Checks whether the cache was initialized successfully.

Throws
androidx.media3.datasource.cache.Cache.CacheException

If an error occurred during initialization.

commitFile

synchronized public void commitFile(File file, long length)

Commits a file into the cache. Must only be called when holding a corresponding hole obtained from startReadWrite.

This method may be slow and shouldn't normally be called on the main thread.

Parameters
File file

A newly written cache file.

long length

The length of the newly written cache file in bytes.

Throws
androidx.media3.datasource.cache.Cache.CacheException

If an error is encountered.

delete

@WorkerThread
public static void delete(File cacheDir, @Nullable DatabaseProvider databaseProvider)

Deletes all content belonging to a cache instance.

This method may be slow and shouldn't normally be called on the main thread.

Parameters
File cacheDir

The cache directory.

@Nullable DatabaseProvider databaseProvider

The database in which index data is stored, or null if the cache used a legacy index.

getCacheSpace

synchronized public long getCacheSpace()

Returns the total disk space in bytes used by the cache.

getCachedBytes

synchronized public long getCachedBytes(String key, long position, long length)

Returns the total number of cached bytes between position (inclusive) and (position + length) (exclusive) of a resource.

Parameters
String key

The cache key of the resource.

long position

The starting position of the data in the resource.

long length

The length of the data to check. LENGTH_UNSET is permitted, and is equivalent to passing MAX_VALUE.

Returns
long

The total number of cached bytes.

getCachedLength

synchronized public long getCachedLength(String key, long position, long length)

Returns the length of continuously cached data starting from position, up to a maximum of maxLength, of a resource. If position isn't cached then -holeLength is returned, where holeLength is the length of continuously uncached data starting from position, up to a maximum of maxLength.

Parameters
String key

The cache key of the resource.

long position

The starting position of the data in the resource.

long length

The maximum length of the data or hole to be returned. LENGTH_UNSET is permitted, and is equivalent to passing MAX_VALUE.

Returns
long

The length of the continuously cached data, or -holeLength if position isn't cached.

getCachedSpans

synchronized public NavigableSet<CacheSpangetCachedSpans(String key)

Returns the cached spans for a given resource.

Parameters
String key

The cache key of the resource.

Returns
NavigableSet<CacheSpan>

The spans for the key.

getContentMetadata

synchronized public ContentMetadata getContentMetadata(String key)

Returns a ContentMetadata for the given resource.

Parameters
String key

The cache key of the resource.

Returns
ContentMetadata

The ContentMetadata for the resource.

getKeys

synchronized public Set<StringgetKeys()

Returns the cache keys of all of the resources that are at least partially cached.

getUid

synchronized public long getUid()

Returns a non-negative unique identifier for the cache, or UID_UNSET if initialization failed before the unique identifier was determined.

Implementations are expected to generate and store the unique identifier alongside the cached content. If the location of the cache is deleted or swapped, it is expected that a new unique identifier will be generated when the cache is recreated.

isCacheFolderLocked

synchronized public static boolean isCacheFolderLocked(File cacheFolder)

Returns whether cacheFolder is locked by a SimpleCache instance. To unlock the folder the SimpleCache instance should be released.

isCached

synchronized public boolean isCached(String key, long position, long length)

Returns whether the specified range of data in a resource is fully cached.

Parameters
String key

The cache key of the resource.

long position

The starting position of the data in the resource.

long length

The length of the data.

Returns
boolean

true if the data is available in the Cache otherwise false;

release

synchronized public void release()

Releases the cache. This method must be called when the cache is no longer required. The cache must not be used after calling this method.

This method may be slow and shouldn't normally be called on the main thread.

releaseHoleSpan

synchronized public void releaseHoleSpan(CacheSpan holeSpan)

Releases a CacheSpan obtained from startReadWrite which corresponded to a hole in the cache.

Parameters
CacheSpan holeSpan

The CacheSpan being released.

removeListener

synchronized public void removeListener(String key, Cache.Listener listener)

Unregisters a listener.

Parameters
String key

The cache key of the resource.

Cache.Listener listener

The listener to remove.

removeResource

synchronized public void removeResource(String key)

Removes all CacheSpans for a resource, deleting the underlying files.

Parameters
String key

The cache key of the resource being removed.

removeSpan

synchronized public void removeSpan(CacheSpan span)

Removes a cached CacheSpan from the cache, deleting the underlying file.

This method may be slow and shouldn't normally be called on the main thread.

Parameters
CacheSpan span

The CacheSpan to remove.

startFile

synchronized public File startFile(String key, long position, long length)

Obtains a cache file into which data can be written. Must only be called when holding a corresponding hole CacheSpan obtained from startReadWrite.

This method may be slow and shouldn't normally be called on the main thread.

Parameters
String key

The cache key of the resource being written.

long position

The starting position in the resource from which data will be written.

long length

The length of the data being written, or LENGTH_UNSET if unknown. Used only to ensure that there is enough space in the cache.

Returns
File

The file into which data should be written.

Throws
androidx.media3.datasource.cache.Cache.CacheException

If an error is encountered.

startReadWrite

synchronized public CacheSpan startReadWrite(String key, long position, long length)

A caller should invoke this method when they require data starting from a given position in a given resource.

If there is a cache entry that overlaps the position, then the returned CacheSpan defines the file in which the data is stored. isCached is true. The caller may read from the cache file, but does not acquire any locks.

If there is no cache entry overlapping position, then the returned CacheSpan defines a hole in the cache starting at position into which the caller may write as it obtains the data from some other source. The returned CacheSpan serves as a lock. Whilst the caller holds the lock it may write data into the hole. It may split data into multiple files. When the caller has finished writing a file it should commit it to the cache by calling commitFile. When the caller has finished writing, it must release the lock by calling releaseHoleSpan.

This method may be slow and shouldn't normally be called on the main thread.

Parameters
String key

The cache key of the resource.

long position

The starting position in the resource from which data is required.

long length

The length of the data being requested, or LENGTH_UNSET if unbounded. The length is ignored if there is a cache entry that overlaps the position. Else, it defines the maximum length of the hole CacheSpan that's returned. Cache implementations may support parallel writes into non-overlapping holes, and so passing the actual required length should be preferred to passing LENGTH_UNSET when possible.

Returns
CacheSpan

The CacheSpan.

Throws
java.lang.InterruptedException

If the thread was interrupted.

androidx.media3.datasource.cache.Cache.CacheException

If an error is encountered.

startReadWriteNonBlocking

synchronized public @Nullable CacheSpan startReadWriteNonBlocking(String key, long position, long length)

Same as startReadWrite. However, if the cache entry is locked, then instead of blocking, this method will return null as the CacheSpan.

This method may be slow and shouldn't normally be called on the main thread.

Parameters
String key

The cache key of the resource.

long position

The starting position in the resource from which data is required.

long length

The length of the data being requested, or LENGTH_UNSET if unbounded. The length is ignored if there is a cache entry that overlaps the position. Else, it defines the range of data locked by the returned CacheSpan.

Returns
@Nullable CacheSpan

The CacheSpan. Or null if the cache entry is locked.

Throws
androidx.media3.datasource.cache.Cache.CacheException

If an error is encountered.