Skip to content

Commit

Permalink
fix: Return new activity holder when scope changes
Browse files Browse the repository at this point in the history
  • Loading branch information
JanCizmar committed Dec 16, 2023
1 parent 4dda635 commit bb5a047
Showing 1 changed file with 23 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import jakarta.annotation.PreDestroy
import org.springframework.beans.factory.support.ScopeNotActiveException
import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Component
import org.springframework.web.context.request.RequestContextHolder

/**
* Class providing Activity Holder, while caching it in ThreadLocal.
Expand All @@ -13,15 +14,23 @@ import org.springframework.stereotype.Component
*/
@Component
class ActivityHolderProvider(private val applicationContext: ApplicationContext) {
private val threadLocal = ThreadLocal<ActivityHolder?>()
private val threadLocal = ThreadLocal<Pair<Scope, ActivityHolder?>>()

fun getActivityHolder(): ActivityHolder {
// Get the activity holder from ThreadLocal.
var activityHolder = threadLocal.get()
var (scope, activityHolder) = threadLocal.get() ?: (null to null)

val currentScope = getCurrentScope()
if (scope != currentScope) {
// If the scope has changed, clear the ThreadLocal and fetch a new activity holder.
clearThreadLocal()
activityHolder = null
}

if (activityHolder == null) {
// If no activity holder exists for this thread, fetch one and store it in ThreadLocal.
activityHolder = fetchActivityHolder()
threadLocal.set(activityHolder)
threadLocal.set(currentScope to activityHolder)
}
return activityHolder
}
Expand All @@ -38,8 +47,19 @@ class ActivityHolderProvider(private val applicationContext: ApplicationContext)
}
}

private fun getCurrentScope(): Scope {
if (RequestContextHolder.getRequestAttributes() == null) {
return Scope.TRANSACTION
}
return Scope.REQUEST
}

@PreDestroy
fun clearThreadLocal() {
threadLocal.remove()
}

enum class Scope {
REQUEST, TRANSACTION
}
}

0 comments on commit bb5a047

Please sign in to comment.