I'm new to Java and is currently reading the book Java: A Beginner's Guide, 6th Edition. I come across some confusions with respect to atomicity and memory order in Java.
In the examples of the book that involving multithreading, concurrent access to shared resources (e.g., a shared variable) is not synchronized, nor are the shared resources specifically marked (e.g, atomic or volatile or something like that). For instance, in Try This 15-1 (page 519), concurrent access to the shared variable stopFlag
is not serialized nor is the variable specifically marked either.
According to this, certain data types in Java are guaranteed to be atomic even if they are not specifically marked. This somewhat solves the consideration concerning atomicity. But how about memory order? Does the default treatment imply sequential-consistency like the default memory_order_seq_cst
treatment on access to atomic types in C++?
Following are some critical code snippet from the example.
public class Banner extends Applet implements Runnable {
String msg = " Java Rules the Web ";
Thread t;
boolean stopFlag;
// Initialize t to null.
public void init() {
t = null;
}
// Start thread
public void start() {
t = new Thread(this);
stopFlag = false;
t.start();
}
// Entry point for the thread that runs the banner.
public void run() {
// Redisplay banner
for( ; ; ) {
try {
repaint();
Thread.sleep(250);
if(stopFlag) break;
} catch(InterruptedException exc) {}
}
}
// Pause the banner.
public void stop() {
stopFlag = true;
t = null;
}
// Display the banner.
public void paint(Graphics g) {
char ch;
ch = msg.charAt(0);
msg = msg.substring(1, msg.length());
msg += ch;
g.drawString(msg, 50, 30);
}