Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can statement n != n returns true in multithread environment [duplicate]

Possible Duplicate:
How to simulate constructor race conditions?
How to demonstrate race conditions around values that aren't published properly?

I got the following code from 《java concurrency in practice》:

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.");

  }


}

I am just wondering the condition n != n, is this could be true under a certain circumstance?

like image 554
Foredoomed Avatar asked Sep 24 '12 05:09

Foredoomed


People also ask

Can we run two threads simultaneously?

Within a process or program, we can run multiple threads concurrently to improve the performance. Threads, unlike heavyweight process, are lightweight and run inside a single process – they share the same address space, the resources allocated and the environment of that process.

Is Java single threaded or multithreaded?

Java is a multi-threaded programming language which means we can develop multi-threaded program using Java.

Which method should be used to append the current threads execution at the end of another thread?

lang. Thread class provides the join() method which allows one thread to wait until another thread completes its execution.

How do you make a thread wait for a condition?

Explanation: When you want to sleep a thread, condition variable can be used. In C under Linux, there is a function pthread_cond_wait() to wait or sleep. On the other hand, there is a function pthread_cond_signal() to wake up sleeping or waiting thread. Threads can wait on a condition variable.


1 Answers

My guess is that you are asking something similar to these questions:

  • How to demonstrate race conditions around values that aren't published properly?
  • How to simulate constructor race conditions?

I'm guessing the book is talking about the possibility of sharing a reference to an object before it is completely constructed, an act referred to is improper publishing.

Suppose that n != n is broken down into the following steps:

Access n on the right side of the operand
Access n on the left side of the operand
Compare values

Then it follows that it is not hard to imagine a case in which the value of n is changed between the first two steps. Now I know what you are thinking, "but n is never changed". Actually, it is, because two threads could share access to an instance of Holder before the constructor for that instance has completely run.

like image 144
Tim Bender Avatar answered Oct 18 '22 20:10

Tim Bender