gpt4 book ai didi

spring - @Synchronized似乎无法同步访问共享资源以进行对Spring Webserver的异步调用

转载 作者:行者123 更新时间:2023-12-02 12:49:35 26 4
gpt4 key购买 nike

我有一个SpringBoot Web服务器;在其上的一条路由,用于控制单例实例的状态。通常由多个参与者调用此路由,因此必须进行同步。
路由调用的相应方法是set():

@Synchronized
public fun <T> set(t: T) {
val incomingState = State.from(t)
if(incomingState == innerState){
return
}
change(incomingState)
}

@Synchronized
private fun change(newState: State){
this.stateAccessLock.lock()
SystemLog.logResourceLocking("HomeState", isLocked = true)
SystemLog.logHomeEvent("Changing HomeState from '${innerState.name}' to '${newState.name}'")
try {
Home.INSTANCE.EXTENSION.broadcastStateChange(
innerState?.name,
newState.name
)
}
finally {
innerState = newState
Home.save()

stateAccessLock.unlock()
SystemLog.logResourceLocking("HomeState", isLocked = false)
}
}
在使用@Synchronized批注之前,我还尝试过在同一类中使用 ReentrantLock(如您所见,到目前为止,我忽略了将其删除)。初始化如下:
private var stateAccessLock = ReentrantLock()

@Autowired
fun HomeState(@Qualifier("stateAccessLock") stateAccessLock: ReentrantLock) {
this.stateAccessLock = stateAccessLock
}
现在, change()中的第三行和最后一行记录了资源锁定并免费提供的资源。过滤这些事件的日志文件可以给我以下信息:
[2020-10-09T16:07:01.709]       LOCK: Resource locked
[2020-10-09T16:07:01.710] LOCK: Resource locked
[2020-10-09T16:07:01.725] LOCK: Resource locked
[2020-10-09T16:07:01.727] LOCK: Resource locked
[2020-10-09T16:07:01.818] LOCK: Resource unlocked
[2020-10-09T16:07:01.828] LOCK: Resource unlocked
[2020-10-09T16:07:01.829] LOCK: Resource unlocked
[2020-10-09T16:07:01.839] LOCK: Resource unlocked
[2020-10-09T16:11:33.499] LOCK: Resource locked
[2020-10-09T16:11:33.523] LOCK: Resource locked
[2020-10-09T16:11:33.525] LOCK: Resource locked
[2020-10-09T16:11:33.692] LOCK: Resource unlocked
[2020-10-09T16:11:33.692] LOCK: Resource unlocked
[2020-10-09T16:11:33.693] LOCK: Resource unlocked
[2020-10-09T16:11:35.881] LOCK: Resource locked
[2020-10-09T16:11:35.959] LOCK: Resource unlocked
显然,我想要这样的东西:
[2020-10-09T16:07:01.709]       LOCK: Resource locked
[2020-10-09T16:07:01.710] LOCK: Resource unlocked
[2020-10-09T16:07:01.725] LOCK: Resource locked
[2020-10-09T16:07:01.727] LOCK: Resource unlocked
[2020-10-09T16:07:01.818] LOCK: Resource locked
[2020-10-09T16:07:01.828] LOCK: Resource unlocked
[2020-10-09T16:07:01.829] LOCK: Resource locked
[2020-10-09T16:07:01.839] LOCK: Resource unlocked
我错过了什么?
提前致谢!

最佳答案

由于您不从这些方法中返回任何内容,因此我将改为进行线程限制并完全放弃锁定。这还将确保您不会陷入僵局:

private val executor = Executors.newSingleThreadExecutor()

fun <T> set(t: T) {
executor.submit {
val incomingState = State.from(t)
if (incomingState == innerState) {
return
}
change(incomingState)
}
}
由于您具有单线程执行程序,因此可以确保以串行方式处理请求(并且没有锁定)。

关于spring - @Synchronized似乎无法同步访问共享资源以进行对Spring Webserver的异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64282162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com