Commit b556c7ea authored by Sebastian Kaspari's avatar Sebastian Kaspari Committed by Jonathan Almeida
Browse files

DiskCache: Synchronize cache writes. Bail out if cache cannot be written.

Fixes https://github.com/mozilla-mobile/fenix/issues/3211

There were two issues with the previous implementation:
* We can't write to the cache concurrently and in this case edit() will
  return null. We should synchronize our writes to avoid not writing
  anything to disk while another write is in-flight.
* In cases where edit() still returns null (stale snapshot) we just
  bail out.
parent e0135030
......@@ -38,6 +38,8 @@ internal class DiskCache :
private val logger = Logger("Icons/DiskCache")
private var iconResourcesCache: DiskLruCache? = null
private var iconDataCache: DiskLruCache? = null
private val iconResourcesCacheWriteLock = Any()
private val iconDataCacheWriteLock = Any()
override fun getResources(context: Context, request: IconRequest): List<IconRequest.Resource> {
val key = createKey(request.url)
......@@ -61,14 +63,16 @@ internal class DiskCache :
internal fun putResources(context: Context, request: IconRequest) {
try {
val key = createKey(request.url)
val editor = getIconResourcesCache(context)
.edit(key)
synchronized(iconResourcesCacheWriteLock) {
val key = createKey(request.url)
val editor = getIconResourcesCache(context)
.edit(key) ?: return
val data = request.resources.toJSON().toString()
editor.set(0, data)
val data = request.resources.toJSON().toString()
editor.set(0, data)
editor.commit()
editor.commit()
}
} catch (e: IOException) {
logger.info("Failed to save resources to disk", e)
} catch (e: JSONException) {
......@@ -102,14 +106,16 @@ internal class DiskCache :
internal fun putIconBitmap(context: Context, resource: IconRequest.Resource, bitmap: Bitmap) {
try {
val editor = getIconDataCache(context)
.edit(createKey(resource.url))
synchronized(iconDataCacheWriteLock) {
val editor = getIconDataCache(context)
.edit(createKey(resource.url)) ?: return
editor.newOutputStream(0).use { stream ->
bitmap.compress(Bitmap.CompressFormat.WEBP, WEBP_QUALITY, stream)
}
editor.newOutputStream(0).use { stream ->
bitmap.compress(Bitmap.CompressFormat.WEBP, WEBP_QUALITY, stream)
}
editor.commit()
editor.commit()
}
} catch (e: IOException) {
logger.info("Failed to save icon bitmap to disk", e)
}
......
......@@ -30,6 +30,9 @@ permalink: /changelog/
* **support-base**
* Fixed multiple potential leaks in `ObserverRegistry` (used internally by many classes in other components like `SessionManager`, `EngineSession` and others).
* **browser-icons**
* Fixed possible `NullPointerException` when disk cache is written to concurrently.
# 0.55.0
* [Commits](https://github.com/mozilla-mobile/android-components/compare/v0.54.0...v0.55.0)
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment