I read a few explanations of section 16.3, "Initializing Security" from JCIP, and is still unclear. The section indicates that
"In addition, any variables that can be reached through the final field of a properly constructed object (for example, the elements of the final array or the HashMap contents referenced by the final field) are visible to other threads are also guaranteed."
So, if I had the following mutable object:
public final class Container{ private String name; private int cupsWon; private double netWorth; public Container( String name, int cupsWon, double netWorth ){ this.name = name; this.cupsWon = cupsWon; this.netWorth = netWorth; }
Then Thread 1 creates it as the following and passes c to Thread2 .
final Container c = new Container("Ted Dibiasi", 10, 1000000);
Thread2 (not at the same time, say, after 1 ms), reads the values of c, is it possible that Thread2 will ever see
c.name=null or c.cupswon=0 or worst of all, c.netWorth=0.0?
Greetings
UPDATE
I noticed that there are getters in the class. I am updating the source code, hope it will be clear. Thanks to everyone for watching.
public final class Container{ private String name; private int cupsWon; private double netWorth; public Container( String name, int cupsWon, double netWorth ){ this.name = name; this.cupsWon = cupsWon; this.netWorth = netWorth; } public final String getName(){ return name; } public final int getCupsWon(){ return cupsWon; } public final double getNetWorth(){ return netWorth; } }
// ----------
public final class Producer{ private final Client client; public Producer( Client client ){ this.client = client; }
// ----
public final class Client{ private Container c;
My questions:
a) When Thread2 calls consume (), can you call cupsWon, netWorth ever equal to null, 0 or 0.0? I thought it was CAN , because the fields in the Container class are not final, there is no guarantee of visibility.
b) However, then I read section 16.3 and a bit about “ variables that can be achieved through the final field of a correctly constructed object ”, does this mean that, since the Container c instance is declared final, we DO have a guarantee of visibility in consumption ()?
final Container c = new container ("Ted Dibiasi", 10, 1,000,000);
c) Declaring a reference to Container in the Client class as a mutable solution to the problem of visibility of fields related to the standard.