synchronize on cache object

This commit is contained in:
Milos Kozak 2021-10-19 21:27:44 +02:00
parent 391cbb575c
commit 674909fdd0

View file

@ -38,7 +38,7 @@ class ProfileFunctionImplementation @Inject constructor(
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
private val config: Config, private val config: Config,
private val hardLimits: HardLimits, private val hardLimits: HardLimits,
private val aapsSchedulers: AapsSchedulers, aapsSchedulers: AapsSchedulers,
private val fabricPrivacy: FabricPrivacy private val fabricPrivacy: FabricPrivacy
) : ProfileFunction { ) : ProfileFunction {
@ -51,8 +51,8 @@ class ProfileFunctionImplementation @Inject constructor(
.toObservable(EventEffectiveProfileSwitchChanged::class.java) .toObservable(EventEffectiveProfileSwitchChanged::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe( .subscribe(
@Synchronized
{ {
synchronized(cache) {
for (index in cache.size() - 1 downTo 0) { for (index in cache.size() - 1 downTo 0) {
if (cache.keyAt(index) > it.startDate) { if (cache.keyAt(index) > it.startDate) {
aapsLogger.debug(LTag.AUTOSENS, "Removing from profileCache: " + dateUtil.dateAndTimeAndSecondsString(cache.keyAt(index))) aapsLogger.debug(LTag.AUTOSENS, "Removing from profileCache: " + dateUtil.dateAndTimeAndSecondsString(cache.keyAt(index)))
@ -61,6 +61,7 @@ class ProfileFunctionImplementation @Inject constructor(
break break
} }
} }
}
}, fabricPrivacy::logException }, fabricPrivacy::logException
) )
} }
@ -92,24 +93,24 @@ class ProfileFunctionImplementation @Inject constructor(
override fun getProfile(): Profile? = override fun getProfile(): Profile? =
getProfile(dateUtil.now()) getProfile(dateUtil.now())
@Synchronized
override fun getProfile(time: Long): Profile? { override fun getProfile(time: Long): Profile? {
val rounded = time - time % 1000
// Clear cache after longer use // Clear cache after longer use
synchronized(cache) {
if (cache.size() > 30000) { if (cache.size() > 30000) {
cache.clear() cache.clear()
aapsLogger.debug("Profile cache cleared") aapsLogger.debug("Profile cache cleared")
} }
val rounded = time - time % 1000
val cached = cache[rounded] val cached = cache[rounded]
if (cached != null) { if (cached != null) return cached
// aapsLogger.debug("HIT getProfile for $time $rounded")
return cached
} }
// aapsLogger.debug("getProfile called for $time") // aapsLogger.debug("getProfile called for $time")
val ps = repository.getEffectiveProfileSwitchActiveAt(time).blockingGet() val ps = repository.getEffectiveProfileSwitchActiveAt(time).blockingGet()
if (ps is ValueWrapper.Existing) { if (ps is ValueWrapper.Existing) {
val sealed = ProfileSealed.EPS(ps.value) val sealed = ProfileSealed.EPS(ps.value)
synchronized(cache) {
cache.put(rounded, sealed) cache.put(rounded, sealed)
}
return sealed return sealed
} }
return null return null