0

Trying to understand the theory about volatile. They say, volatile provides happens-before, so changes done in thread 1 should be visible in thread 2.

What if we will put volatile for Collection? Will java provide visibility in Thread 2 for changes done in Thread 1 ? And why?

public class Vol {
    volatile List<String> list = new ArrayList<>();
    
    // thread 1
    public void put(String s) {
        list.add(s);
    }
    
    // thread 2
    public List<String> get(){ // all changes are visible? "Why" for No\Yes answer
        return list;
    }
}
VextoR
  • 5,087
  • 22
  • 74
  • 109
  • 3
    The keyword `volatile` describes the reference, not the object to which it points. You can create a thread-safe list with `Collections.synchronizedList( new ArrayList<>())`, or the older class `Vector`. – Andy Thomas May 06 '22 at 21:28
  • 2
    Who is “they”? Why should we care about what “they say” when you can’t name them nor provide a link to a source? – Holger May 09 '22 at 12:55

0 Answers0