The question was sent before , but no real example was presented that would work. Therefore, Brian mentions that under certain conditions AssertionError can occur in the following code:
public class Holder {
private int n;
public Holder(int n) { this.n = n; }
public void assertSanity() {
if (n!=n)
throw new AssertionError("This statement is false");
}
}
If the owner is incorrectly published as follows:
class someClass {
public Holder holder;
public void initialize() {
holder = new Holder(42);
}
}
I understand that this will happen when the reference to the holder becomes visible before the instance variable of the object holder becomes visible to another thread. Therefore, I made the following example to provoke this behavior and therefore an AssertionError with the following class:
public class Publish {
public Holder holder;
public void initialize() {
holder = new Holder(42);
}
public static void main(String[] args) {
Publish publish = new Publish();
Thread t1 = new Thread(new Runnable() {
public void run() {
for(int i = 0; i < Integer.MAX_VALUE; i++) {
publish.initialize();
}
System.out.println("initialize thread finished");
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
int nullPointerHits = 0;
int assertionErrors = 0;
while(t1.isAlive()) {
try {
publish.holder.assertSanity();
} catch(NullPointerException exc) {
nullPointerHits++;
} catch(AssertionError err) {
assertionErrors ++;
}
}
System.out.println("Nullpointerhits: " + nullPointerHits);
System.out.println("Assertion errors: " + assertionErrors);
}
});
t1.start();
t2.start();
}
}
No matter how many times I run the code, an AssertionError never occurs. Therefore, for me there are several options:
- jvm ( Oracle 1.8.0.20) , , , .
- , , ... nuf
- -
, :
- - - AssertionError? ?
- AssertionError?