Ouney
Ouney

Reputation: 1194

Data sharing (class level) among multiple threads

Need your help to get my basics right. Please consider the following fragment (from a book :) )

class Flooring extends Thread
{

  final int MAX = 100000000;
  int number;
  volatile double d = 0;

  public Flooring(int n, int priority)
  {
    number = n;
    setPriority(priority);
    start(); // start the thread
  }

  public void run()
  {
    for(int i = 1; i < MAX; i++)
      d = d + (Math.PI + Math.E + Math.floor(i)) / (double)i;
    System.out.println(“Inside Thread” + number + “ : ” + d);
  }
}

public class FloorThread
{
  public static void main(String[] args)
  {
    for(int i = 1; i < 11; i++)
      new Flooring(i, 11-i); // priority decreases
  }
}

Here variable d is marked as volatile. which means that we want to ensure visibility among threads and hence it is a shared variable. I have seen some other examples where in we have a variable in Thread class but not expected to share?? Shouldn't every new Flooring object should have its own double d variable??

Please help as i got confused with similar other examples not marking the same kind of variables as volatile.

Thanks in advance.

Upvotes: 0

Views: 54

Answers (1)

KC-NH
KC-NH

Reputation: 748

I don't see any reason for d to be volatile. Each instance has it's own copy. You could even make d local to the run method.

Upvotes: 3

Related Questions