does volatile works on object reference

hi all,

i am a bit confused on the usage of volatile keyword. consider the following statement

publicclass Me

{

public Me()

{

primitive = 0;

vector =new Vector(100);

}

volatileint primitive;

volatile Vector vector;

}

Says there are two Thread A and B, A modify primitive value to 100. B tries to read primitive value. B will get the latest primiteve value (100) since B is reading directly from true primitive memory location, not its cache.

(Please correct me if the above statement is wrong)

For point object reference, A trying to change the object reference to a new Vector(200). B tries to read point. B will get the latest Vector(200) object since B is reading directly from true vector object reference memory location, not its cache.

(Please correct me if the above statement is wrong)

However, how about the elements inside the vector itself? Says A try to change the vector element by vector.setElementAtLocation("new value", 37). When B tries to access the vector element at 37th, will it read directly from the true vector 37th element memory location, or there is a possibility B will read from 37th element cache memory?

Hence, is it safe, that we declare a vector as volatile, and assume that all threads is able to get its most updated "element value"?

Thank you very much!

cheok

[1754 byte] By [KwangHooia] at [2007-11-27 1:41:51]
# 1

Going through the JLS, they say nothing specific to object references. All the examples tend to use ints.

Vector might be a bad object to use as well, since it's synchronized.

Let's change it to ArrayList. I would say that a volatile ArrayList could have it's contents dirty, since only the arraylist reference is volatile, not the references to it's elements.

But this is only an educated guess. I guess someone should scrounge the [url="http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.3.1.4"]JLS[/url] a bit better.

-Kayaman-a at 2007-7-12 0:57:43 > top of Java-index,Java Essentials,Java Programming...