为什么Scala Actor实现涉及同步代码?
我的理解是,基于队列的并发方法可以在没有锁定的情况下实现。但我在 Actor.scala 文件中看到很多同步关键字(查看 2.8.1)。是否同步,是否有必要,如果存在未同步的实现,会有什么不同吗?
显然这个问题还不够清楚:我的理解是这可以通过非阻塞队列来实现。为什么没有这样做呢?为什么在这里使用同步关键字?可能有一个很好的理由,也可能只是因为事情就是这样做的,而没有必要。我只是好奇是哪个。
My understanding is that the queue based approach to concurrency can be implemented without locking. But I see lots of synchronized keywords in the Actor.scala file (looking at 2.8.1). Is it synchronized, is it necessary, would it make a difference if there was an implementation that was not synchronized?
Apparently the question wasn't clear enough: my understanding is that this can be implemented with a non-blocking queue. Why was it not done so? Why use the synchronized keyword anywhere in here? There may be a very good reason, or it might be just because that's the way it was done and it's not necessary. I was just curious which.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要点是,您在“act”方法中编写的反应不需要关注同步。另外,假设您不公开参与者的状态,您的程序将是完全线程安全的。
这并不是说根本没有同步:同步是绝对必要的 [1] 来实现对参与者邮箱的读/写访问(即发送和接收消息)并且还确保参与者的私有状态在任何后续反应中保持一致。
这是由库本身实现的,您(用户)无需关心它是如何完成的。由于 JMM 的 发生在 保证,您的状态是安全的(您甚至不需要使用易失性字段)。也就是说,如果主存储器写入发生在同步点之前,则同步之后发生的任何读取都将观察写入留下的主存储器状态。
[1] - 我所说的“同步”是指保证 Java 内存模型中发生先发生关系的某种机制。这包括
synchronized
关键字、volatile
修饰符和/或java.util.concurrent
锁定原语The point is that the reactions, which you write in the "act" method, do not need to concern themselves with synchronization. Also, assuming that you do not expose the actor's state, your program will be fully thread safe.
That is not to say that there is no sync at all: synchronization is absolutely necessary [1] to implement read/write access to the actor's mailbox (i.e. the sending and receiving of messages) and also to ensure the actor's private state is consistent across any subsequent reacts.
This is achieved by the library itself and you, the user, need not concern yourself with how it is done. Your state is safe (you don't even need to use volatile fields) because of the JMM's happens before guarantees. That is, if a main-memory write happens before a sync point, then any read occurring after a sync will observe the main memory state left by the write.
[1] - by "synchronization", I mean some mechanism to guarantee a happens-before relationship in the Java Memory Model. This includes the
synchronized
keyword, thevolatile
modifier and/or thejava.util.concurrent
locking primitives