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,14 +51,15 @@ class ProfileFunctionImplementation @Inject constructor(
.toObservable(EventEffectiveProfileSwitchChanged::class.java) .toObservable(EventEffectiveProfileSwitchChanged::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe( .subscribe(
@Synchronized
{ {
for (index in cache.size() - 1 downTo 0) { synchronized(cache) {
if (cache.keyAt(index) > it.startDate) { for (index in cache.size() - 1 downTo 0) {
aapsLogger.debug(LTag.AUTOSENS, "Removing from profileCache: " + dateUtil.dateAndTimeAndSecondsString(cache.keyAt(index))) if (cache.keyAt(index) > it.startDate) {
cache.removeAt(index) aapsLogger.debug(LTag.AUTOSENS, "Removing from profileCache: " + dateUtil.dateAndTimeAndSecondsString(cache.keyAt(index)))
} else { cache.removeAt(index)
break } else {
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? {
// Clear cache after longer use
if (cache.size() > 30000) {
cache.clear()
aapsLogger.debug("Profile cache cleared")
}
val rounded = time - time % 1000 val rounded = time - time % 1000
val cached = cache[rounded] // Clear cache after longer use
if (cached != null) { synchronized(cache) {
// aapsLogger.debug("HIT getProfile for $time $rounded") if (cache.size() > 30000) {
return cached cache.clear()
aapsLogger.debug("Profile cache cleared")
}
val cached = cache[rounded]
if (cached != null) 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)
cache.put(rounded, sealed) synchronized(cache) {
cache.put(rounded, sealed)
}
return sealed return sealed
} }
return null return null