實現Java虛擬機需要考慮的一件事情是,字段之間以及數組元素之間是獨立的,更新一個字段或元素不能影響任何其它字段或元素的讀取與更新。尤其是,兩個線程在分別更新byte數組相鄰的元素時,不能互相影響與干擾,且不需要同步來保證順序一致性。
有些處理器沒有提供寫單個字節的功能。在這樣的處理器上更新byte數組,若只是簡單地讀取整個字,更新對應的字節,然後將整個字再寫回內存,這種做法是違反規則的。這個問題有時候被稱爲“字分裂(word tearing)”,在單獨更新單個字節有難度的處理器上,就需要尋求其它方式了。
public class WordTearing extends Thread {
static final int LENGTH = 8;
static final int ITERS = 1000000;
static byte[] counts = new byte[LENGTH];
static Thread[] threads = new Thread[LENGTH];
final int id;
WordTearing(int i) {
id = i;
}
public void run() {
byte v = 0;
for (int i = 0; i < ITERS; i++) {
byte v2 = counts[id];
if (v != v2) {
System.err.println("Word-Tearing found: " +
"counts[" + id + "] = "+ v2 +
", should be " + v);
return;
}
v++;
counts[id] = v;
}
}
public static void main(String[] args) {
for (int i = 0; i < LENGTH; ++i)
(threads[i] = new WordTearing(i)).start();
}
}