Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,18 @@ import kotlin.collections.ArrayList
class ValidationServiceFactoryImpl : ValidationServiceFactory {
private val validationServiceConfig: ValidationServiceConfig = ValidatorApplicationConfig.validationServiceConfig
private var sessionCacheFactory: SessionCacheFactory = SessionCacheFactoryImpl()
@Volatile
private var validationService: ValidationService
private var presets: List<Preset>

private val reloadLock = java.util.concurrent.locks.ReentrantLock()
private var lastReloadTime: Long = 0
private val RELOAD_COOLDOWN_MS = java.util.concurrent.TimeUnit.MINUTES.toMillis(5)

init {
presets = loadPresets();
validationService = createValidationServiceInstance();
lastReloadTime = System.currentTimeMillis()
}

private fun createValidationServiceInstance(): ValidationService {
Expand Down Expand Up @@ -72,13 +78,30 @@ class ValidationServiceFactoryImpl : ValidationServiceFactory {
}

override fun getValidationService() : ValidationService {
if (java.lang.Runtime.getRuntime().freeMemory() < validationServiceConfig.engineReloadThreshold) {
println(
"Free memory ${
java.lang.Runtime.getRuntime().freeMemory()
} is less than ${validationServiceConfig.engineReloadThreshold}. Re-initializing validationService"
);
validationService = createValidationServiceInstance();
val freeMemory = java.lang.Runtime.getRuntime().freeMemory()
if (freeMemory < validationServiceConfig.engineReloadThreshold) {
val now = System.currentTimeMillis()
// Try to acquire lock. If we can't, another thread is already reloading it, so just return the existing one.
if (reloadLock.tryLock()) {
try {
// Double check time and memory inside the lock
if (java.lang.Runtime.getRuntime().freeMemory() < validationServiceConfig.engineReloadThreshold &&
(now - lastReloadTime) > RELOAD_COOLDOWN_MS) {

println(
"Free memory ${
java.lang.Runtime.getRuntime().freeMemory()
} is less than ${validationServiceConfig.engineReloadThreshold} and cooldown passed. Re-initializing validationService"
);
validationService = createValidationServiceInstance();
lastReloadTime = System.currentTimeMillis()
}
} finally {
reloadLock.unlock()
}
} else {
println("Memory is low ($freeMemory), but another thread is currently re-initializing the engine. Skipping.")
}
}
return validationService;
}
Expand Down