3 回答

TA貢獻1877條經(jīng)驗 獲得超6個贊
這是從scala郵件列表中獲取的,并lazy根據(jù)Java代碼(而非字節(jié)碼)提供了實現(xiàn)細節(jié):
class LazyTest {
lazy val msg = "Lazy"
}
被編譯為等效于以下Java代碼的內(nèi)容:
class LazyTest {
public int bitmap$0;
private String msg;
public String msg() {
if ((bitmap$0 & 1) == 0) {
synchronized (this) {
if ((bitmap$0 & 1) == 0) {
synchronized (this) {
msg = "Lazy";
}
}
bitmap$0 = bitmap$0 | 1;
}
}
return msg;
}
}

TA貢獻1824條經(jīng)驗 獲得超5個贊
使用Scala 2.10,像這樣的惰性值:
class Example {
lazy val x = "Value";
}
被編譯為類似于以下Java代碼的字節(jié)代碼:
public class Example {
private String x;
private volatile boolean bitmap$0;
public String x() {
if(this.bitmap$0 == true) {
return this.x;
} else {
return x$lzycompute();
}
}
private String x$lzycompute() {
synchronized(this) {
if(this.bitmap$0 != true) {
this.x = "Value";
this.bitmap$0 = true;
}
return this.x;
}
}
}
請注意,位圖由表示boolean。如果添加另一個字段,則編譯器將增加該字段的大小,使其能夠表示至少2個值,即表示為byte。這僅適用于大量課程。
但是您可能想知道為什么這可行?進入同步塊時,必須清除線程本地緩存,以便將非易失性x值刷新到內(nèi)存中。這篇博客文章給出了解釋。
- 3 回答
- 0 關(guān)注
- 789 瀏覽
添加回答
舉報