0

I got two threads running on Main.java and a boolean field Main.bool which is false in the beginning. The first thread will set Main.bool to true. After that, The second thread will print out Main.bool. And the result is FALSE.

More interesting, I tried to print out a random text before printing Main.bool, then the result turned out to be correct(true).

Anyone have an idea what is going on here? I'm using eclipse Kepler.

Main.bool = false;
thread1.setBool(true);
// then wait for some seconds
// case 1
thread2.printBool(); --> false
// case 2
System.out.println("blah blah");
thread2.printBool(); --> true
Aliencc
  • 89
  • 1
  • 6

2 Answers2

0

Make your filed 'bool' as volatile.

Any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable

For more info.

Note: Making a field volatile, ensures that anyone who is reading the value of that field reads it from the memory and not from the local copy.

Aditya
  • 1,324
  • 1
  • 12
  • 22
  • yes thank you, I do know about volatile field, I just don't understand why it happened that way, and yours seems to be the right answer:) – Aliencc Mar 05 '14 at 07:08
0

Form JLS-8.3.1.4

The Java programming language provides a second mechanism, volatile fields, that is more convenient than locking for some purposes.

A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable

For more details see:

  1. Atomic Access
  2. What are Transient and Volatile Modifiers
Community
  • 1
  • 1
Sumit Singh
  • 24,095
  • 8
  • 74
  • 100