-
Notifications
You must be signed in to change notification settings - Fork 322
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add case instruction reordering causes
non-final
field variab…
…le read error (#64)
- Loading branch information
1 parent
042b533
commit f599bfe
Showing
3 changed files
with
94 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
47 changes: 47 additions & 0 deletions
47
src/main/java/fucking/concurrency/demo/FinalInitialDemo.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
package fucking.concurrency.demo; | ||
|
||
|
||
/** | ||
* @author hyy (hjlbupt at 163 dot com) | ||
*/ | ||
public class FinalInitialDemo { | ||
|
||
private int a; | ||
private boolean flag; | ||
private FinalInitialDemo demo; | ||
|
||
public FinalInitialDemo() { | ||
a = 1; | ||
flag = true; | ||
} | ||
|
||
public void writer() { | ||
demo = new FinalInitialDemo(); | ||
} | ||
|
||
public void reader() { | ||
if (flag) { | ||
int i = a * a; | ||
if (i == 0) { | ||
// On my dev machine, the variable initial always success. | ||
// To solve this problem, add final to the `a` field and `flag` field. | ||
System.out.println("Fuck! instruction reordering occurred."); | ||
} | ||
} | ||
} | ||
|
||
@SuppressWarnings("InfiniteLoopStatement") | ||
public static void main(String[] args) throws Exception { | ||
while (true) { | ||
FinalInitialDemo demo = new FinalInitialDemo(); | ||
Thread threadA = new Thread(demo::writer); | ||
Thread threadB = new Thread(demo::reader); | ||
|
||
threadA.start(); | ||
threadB.start(); | ||
|
||
threadA.join(); | ||
threadB.join(); | ||
} | ||
} | ||
} |