s.one.ice s.one.ice - 2 months ago 10
Java Question

if a value is set by 'set' method of Class java.lang.reflect.Field, does it have visibility in concurrency?

In java doc of this method, concurrency is not mentioned, so it seems that the 'set' method do not ensure visibility. I'm not sure about this.

In fact, I have encountered a difficulty because of this question. I'm going to build a distribute configuration platform based on zookeeper. Like the other configuration platform, if a field is annotated by a specific annotation, the platform will mapping this field to a node in zookeeper. Once the value of the mapped node is changed, project using this platform will be informed by zookeeper watcher and change the annotated field using reflection(by 'set' method).

The project using my configuration platform is likely to be a web application, which has one and only one object in service layer, so the field is always accessed in concurrency. if the 'set' method do not ensure visibility, do I must force the project add Keyword volatile for the annotated field ? I looks strange and tedious. Is there some better way about this problem ? How do the other configuration platforms solving this ?

Answer

In java doc of this method, concurrency is not mentioned, so it seems that the 'set' method do not ensure visibility. I'm not sure about this.

Calling a set method through reflection has nothing to do with concurrency, it is about accessibility. The concurrency is about how the field is specifically marked up. Is it a volatile field, one of the Atomic... classes, etc.?

If one thread calls the set method in any way (setFoo() method, via reflection, or other code) then other threads may not see this updated value until the thread doing the writing crosses a write memory barrier to ensure publishing to main memory and the other threads cross a read barrier to ensure that their per-processor memory caches are updated.

If the 'set' method do not ensure visibility, do I must force the project add Keyword volatile for the annotated field ?

Yes you do. For any field that you want to share between threads you will need to figure out how the field gets synchronized.

I looks strange and tedious. Is there some better way about this problem ? How do the other configuration platforms solving this ?

The answer to this depends a bit on your requirements. If you need this field updated to the most recent value on every access then marking it volatile or switching to an Atomic* class is your answer (not sure why adding the keyword is "tedious").

Another mechanism you could use is to have each request update some sort of configuration object at the start of the request in a synchronized manner and then use it's cached config object while the request is being handled.

Comments