Search code examples
javaconcurrencyvolatile

java volatile used with jave linked list


Is it correct that the items that I added in my constructor to my volatile linked list below may not be visible to other threads

class ProductPrice {
  private volatile LinkedList<QuantityPrice> quantityPriceList;
  public ProductPrice(List<QuantityPrice> quantityPriceListParam) {
      this.quantityPriceList = new LinkedList<QuantityPrice>();
      quantityPriceList.addAll(quantityPriceListParam);
  }
}

Would the following code where i assign the volatile variable after the list is loaded fix the issue. Because all happen before operations would also be visible.

private volatile LinkedList<QuantityPrice> quantityPriceList;
public ProductPrice(List<QuantityPrice> quantityPriceListParam) {
    LinkedList<QuantityPrice> tempQuantityLinkedList = new LinkedList<QuantityPrice>();
    tempQuantityLinkedList.addAll(quantityPriceListParam);
    this.quantityPriceList = tempQuantityLinkedList;
}

and in this case could i just make the variable final and get the same effect of having all items visible to other threads.

private final LinkedList<QuantityPrice> quantityPriceList;
public ProductPrice(List<QuantityPrice> quantityPriceListParam) {
    LinkedList<QuantityPrice> tempQuantityLinkedList = new LinkedList<QuantityPrice>();
    tempQuantityLinkedList.addAll(quantityPriceListParam);
    this.quantityPriceList = tempQuantityLinkedList;
}

Solution

  • Is it correct that the items that I added in my constructor to my volatile linked list below may not be visible to other threads

    If the list is non-null, then all the writes to the list will be visible. There is a race condition in which the default write (null) may be visible to a thread seeing a non-null ProductPrice. This isn't true if the field is final.

    and in this case could i just make the variable final and get the same effect of having all items visible to other threads.

    Yes, this is the best solution.