Oct 31st, 2011, 08:21 AM
Dependency injection and memory model
Lastly I've been considering possible memory-consistency issues related to Spring dependency injection.
The thing is, if I use getters and setters for injected dependencies and the attributes holding this dependencies are not declared volatile, can I be 100% sure (from a 100% spec-standard point of view) that there can be no memory-consistency issues?
Spring initialization is done by one thread (or more) and then multiple threads access created beans. Theoretically, if one thread can set a property and another one can read it, you must use either synchronization or volatile variables to ensure that write by one thread "happens before" read by another one.
I'm not sure if the standard says anything about threads being started "after" a non-volatile variable has been assigned neither whether Spring starts any thread that can access a given bean after it has been initialized.
Is this (theoretically) a possible issue? Is Spring doing anything to ensure memory consistency?
Right now, just to be paranoid, for critical beans, I'm using initialization through constructor parameters and using final attributes, that since Java 5 ensure the "happens before" relation, but this is obviously less flexible and disallows the possibility to change configuration without restarting the application.
Thanks a lot.
Tags for this Thread