Skip to content

Commit

Permalink
Using semaphore rather than synchronizing on generic object.
Browse files Browse the repository at this point in the history
  • Loading branch information
cafesilencio committed Jun 25, 2024
1 parent 9b40acb commit a89e1c4
Showing 1 changed file with 20 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.mapbox.navigation.base.internal.route
import android.util.LruCache
import com.mapbox.api.directions.v5.models.DirectionsRoute
import com.mapbox.navigation.base.route.NavigationRoute
import java.util.concurrent.Semaphore

/**
* **Internal** cache object that aims to improve the performance performance of compatibility functions
Expand All @@ -17,37 +18,51 @@ import com.mapbox.navigation.base.route.NavigationRoute
object RouteCompatibilityCache {
private val directionsSessionCache = mutableListOf<NavigationRoute>()
private val creationCache = LruCache<DirectionsRoute, NavigationRoute>(3)
private val lock = Any()
private val semaphore = Semaphore(1)

/**
* Use to put a result of a random route creation to cache.
*/
fun cacheCreationResult(routes: List<NavigationRoute>) {
synchronized(lock) {
if (safelyAcquire()) {
routes.forEach {
creationCache.put(it.directionsRoute, it)
}
semaphore.release()
}
}

/**
* Use to put all routes tracked by `MapboxDirectionsSession` to cache (and clear everything else).
*/
fun setDirectionsSessionResult(routes: List<NavigationRoute>) {
synchronized(lock) {
if (safelyAcquire()) {
creationCache.evictAll()
directionsSessionCache.clear()
directionsSessionCache.addAll(routes)
semaphore.release()
}
}

/**
* Get a cached [NavigationRoute] if there is one that wraps the provided [DirectionsRoute] (based on equality) or `null`.
*/
fun getFor(directionsRoute: DirectionsRoute): NavigationRoute? {
synchronized(lock) {
return directionsSessionCache.find { it.directionsRoute == directionsRoute }
var toReturn: NavigationRoute? = null
if (safelyAcquire()) {
toReturn = directionsSessionCache.find { it.directionsRoute == directionsRoute }
?: creationCache.get(directionsRoute)
semaphore.release()
}
return toReturn
}

private fun safelyAcquire(): Boolean {
return try {
semaphore.acquire()
true
} catch (ex: Exception) {
false
}
}
}

0 comments on commit a89e1c4

Please sign in to comment.