3

Imagine we have

volatile int publisher = 0;
volatile List<String> list = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
volatile String[] array = {"Buenos Aires", "Córdoba", "La Plata"};

As far as I understand.

Initial values in list and array are published correctly and are visible to all the reading threads.

All values added after the initialization are not safe-published.

Still we can read and publish them safely using

//in Thread 1
list.add("Safe City");
array[2] = "Safe city";
publisher = 1;

//in Thread2

if(publisher == 1) {
String city = list.get(3);
city = array[2];
}

Am I right?

4
  • Note that the volatile keyword applies to the list or array variable itself, not to the contents of the list or array. Aug 29, 2014 at 19:16
  • It's not clear what you're asking here. For primitives, volatile refers to the primitive value itself. For objects, the volatile keyword refers only to the reference, not the object referred to. So for list and array, volatile does not have any effect on the contents of the list or array. volatile does not do what what you seem to think it does. Aug 29, 2014 at 19:17
  • 1
    @JimGarrison in Java 1.5 and newer, volatile guarantees visibility of all the changes made before the assignment to volatile, not just the changes in the vloatile itself. So it can be relevant.
    – user3458
    Aug 29, 2014 at 19:22
  • 1
    Note that you cannot add or remove elements from the List returned by Arrays.asList; you can only set elements without changing the size of the list. This is mostly irrelevant to the memory model issues you're asking about though. Aug 29, 2014 at 23:29

4 Answers 4

9

Looking strictly at what the code is doing, and nothing more, and assessing it only in terms of the memory model, you are correct. The write to the volatile variable publisher in thread 1 and the read from the volatile variable in thread 2 establish a happens-before relationship, so all previous writes from thread 1 will be visible to subsequent reads from thread 2.

As CupawnTae noted, it's not necessary for the list and the array to be volatile in order for this to hold. Only publisher needs to be volatile.

Looking at this from a broader perspective, it's very difficult to extend this code to do anything else. (Set aside the fact that the List returned by Arrays.asList cannot have elements added to it; assume it's an ArrayList instead.) Presumably thread 1, or some other thread, will want to continue to add elements to the list. If this happens to cause the ArrayList to reallocate its underlying array, this might occur while thread 2 is still reading results from the previous addition. Thus, inconsistent state might be visible to thread 2.

Suppose further that thread 1 wants to do subsequent updates. It will have to set publisher to some other value, say 2. Now how do reading threads know what the correct value is to test for? Well, they can read the expected value from some other volatile variable....

It's undoubtedly possible to construct a scheme where thread 1 can write to a list (or array) at will, and thread 2 will never see anything but consistent snapshots, but you have to be exceptionally careful about memory visiblity at every step of the way. At a certain point it's easier just to use locks.

5

That is correct, but...

The volatile keyword on the list and array are irrelevant here - the fact that you write a value to the volatile publisher after you write the other values, and read back that value in your if condition before reading the other values in the second thread guarantees you memory consistency between those threads.

If you remove the volatile keyword from the list and array, your code will still be safe.

If you remove the publisher variable write/read, then the add operation* and array assignment are no longer safe.

And yes, the initial assignment to the variables is also safe.

* which is actually invalid on that particular list anyway as pointed out by Stuart Marks, but let's assume it's e.g. an ArrayList

5
  • Thanks CupawnTae, but if I dont have a "publisher" at all - am I correct in these: "Initial values in list and array are published correctly and are visible to all the reading threads. All values added after the initialization are not safe-published" ?
    – MiamiBeach
    Aug 30, 2014 at 7:42
  • @Dymytry please see updated answer - I've gone into more detail and it should clarify
    – CupawnTae
    Aug 30, 2014 at 8:58
  • 1
    “if you add a write to the volatile variables, even if the value doesn't change, it will become safe again” — this is wrong. If the reading thread is not capable of detecting whether the write has happened (which is impossible if the value is the same), then there is no happens-before relationship. A write to a volatile variable does not cause other threads reading that variable to wait for the write to happen. The code in the question does it right as the transition of publisher from 0 to 1 is detectable and checked by the reading thread. Without that, it would be broken.
    – Holger
    Sep 2, 2014 at 16:54
  • @Holger interesting point. I guess my definition of "safe" was a bit loose here. While the reading thread will be guaranteed a consistent picture at the time they read the variable, there is nothing stopping another thread modifying the collection after that. However, the publisher check doesn't stop that occurring either, does it? Writer makes changes, updates publisher, reader sees change, reads variable, writer makes more changes, reader reads inconsistent data? Either way, I removed that section, because it was misleading if not completely wrong. Thanks.
    – CupawnTae
    Sep 2, 2014 at 20:11
  • @CupawnTae: Right, any subsequent modification enables the possibility of data races and subsequent writes to the volatile variable do not help then. Guarding with a volatile variable is a one-time op. That’s why Stuart Marks said “it's very difficult to extend this code to do anything else”.
    – Holger
    Sep 2, 2014 at 21:11
0

The "publishing" happens between the thread that sets the volatile value and teh thread that gets it.

You need to both

publisher = 1;

in one thread and

int local = publisher;

in the other.

1
  • the if (publisher==1) that's already in the question is sufficient to satisfy the second constraint
    – CupawnTae
    Aug 29, 2014 at 19:29
0

Have you considered using synchronized blocks to provide locking of the data structures that you're trying to read/write to/from?

//in Thread 1
synchronized(someLockingMonitor) {
    list.add("Safe City");
    array[2] = "Safe city";
}

//in Thread2
synchronized(someLockingMonitor) {
    String city = list.get(3);
    city = array[2];
}

This will however force any thread wishing to access one of the blocks, to wait until any other thread currently executing inside one of these block to leave the block.

If concurrency is important to you, i.e. you really want different threads reading and writing at the same time, have a look at the concurrent collections in java.util.concurrent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.