精美的Twitter util库具有以下Java类,该类由Scala类扩展,该类读取volatile字段并使用AtomicReferenceFieldUpdater对其进行更新.访问必须至少是私有的,即必须允许other.state.
评论中的动机主张是真的吗?太对了?("如何"意味着以何种方式和程度.)
public class IVarField<A> {
/** This is needed because we cannot create a field like this in Scala. */
volatile State<A> state;
}
Run Code Online (Sandbox Code Playgroud)
som*_*ytt 14
类似下面的工作.
使字段"private [this]"将其转换为所需的字段引用("getfield").
来自不同实例的访问是通过访问者"state()"进行的,如果使用@inline,它将很乐意放松对该字段的访问限制.
这也意味着更新程序(碰巧驻留在配套模块中)也可以访问它.
(因为对象私有成员不会发出var的普通访问器,所以你可以使用parens定义自己的.但你不需要在呼叫站点使用parens,other.state.你的统一访问原则美元在工作.或瑞士法郎.)
还要注意`new`参数名称中反引号的完全髋关节用法.我甚至不知道如何在这个标记中显示标记.因为两个参数都是相同的类型,一个人可能想要写cas(expect=prev, `new`=changed),所以我可能会使用next,但如果这个标记支持一个时髦的大拇指,我现在就给它.:+1:它有用吗?谁能看到我的拇指?[我想我在github上看到了这一点.Hubster,不是时髦.]
object IVar {
// TODO: retrieve mangled name by reflection
private final val stateField = "com$twitter$concurrent$IVar$$state"
private val stateUpd = AtomicReferenceFieldUpdater.newUpdater(
classOf[IVar[_]], classOf[State[_]], stateField)
}
final class IVar[A] { //}extends IVarField[A] {
import IVar._
@volatile private[this] var state: State[A] = initState: State[A]
@inline private final def state(): State[A] = this.state
override def toString = "Ivar@%s(state=%s)".format(hashCode, state)
@inline private[this]
def cas(expect: State[A], `new`: State[A]) = stateUpd.compareAndSet(this, expect, `new`)
def depth: Int = {
@tailrec
def loop(iv: IVar[_], d: Int): Int = iv.state match {
case Linked(iv) => loop(iv, d + 1)
case _ => d
}
loop(this, 0)
}
// etc
}
Run Code Online (Sandbox Code Playgroud)
显示state()实际上是内联的:
private final int loop$1(com.twitter.concurrent.IVar, int);
flags: ACC_PRIVATE, ACC_FINAL
Code:
stack=3, locals=5, args_size=3
0: aload_1
// Field com$twitter$concurrent$IVar$$state:Lcom/twitter/concurrent/ivar/State;
1: getfield #16
4: astore_3
Run Code Online (Sandbox Code Playgroud)
不仅"可以提出并回答你自己的问题",
http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/
它更令人满意.
(Daniel Sobral,Rex Kerr,Retronym和其他正义联盟的更多权力.)
| 归档时间: |
|
| 查看次数: |
635 次 |
| 最近记录: |