0

Java: I have shared variable(of type Object) whose value will be changed very frequently by different threads. Accessing this variable's value from other method by some other set of threads, will give any corrupted value (the value that is not at all assigned) ? Does any problem will happen when the variable is accessed at the time of reference swapping ???

// this method will be called very frequently
public void changeValue(Object value)
{
    this.value = value;
}

// will this method call return an invalid memory reference ?
public Object getValue()
{
    return value;
}
krishna
  • 807
  • 2
  • 11
  • 19

6 Answers6

4

Assigning a new Object to a variable is an atomic operation, but if you don't make the reference volatile, or synchronize access to this reference, or use an AtomicReference, you will have visibility problems and see stale values.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Visibility problem? Do you mean like the new value won't be visible. – krishna Sep 28 '12 at 06:09
  • 1
    Yes. In multi-core architectures, each core has its cache, and writing to a variable in a thread doesn't guarantee that the other threads will see the new value, because they might still see the value stored in their processor cache. The use of volatile, synchronized or atomic references solves this proble. Read http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html#MemoryVisibility – JB Nizet Sep 28 '12 at 08:23
1

The object reference is handled in an atomic operation. See Java Language Specification 17.4 and the excellent answer here.

Community
  • 1
  • 1
Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53
0

The getter will always return a valid object (or null, if none has been set). It may return the older value. If you want to counter that, you can add synchronized to the method. But this will make threads wait for each other when setting

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
0

The value will be a valid object, even when being modified concurrently.

However, if you try to do this with a java.util.List, java.util.Map, or other collection holder, you will encounter a ConcurrentModificationException if you modify the collection's value set while iterating through it in another thread, in which case your best approach is to either modify your getter and setter methods with the synchronized keyword, or use a synchronized block on the collection itself.

FThompson
  • 28,352
  • 13
  • 60
  • 93
0

Use AtomicReference to store your value variable.

FThompson
  • 28,352
  • 13
  • 60
  • 93
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72
0

Now problem, provided you declared value as volatile or access methods as synchronized.

Alexei Kaigorodov
  • 13,189
  • 1
  • 21
  • 38