I read this in an upvoted comment on StackOverflow:
But if you want to be safe, you can add simple synchronized(this) {} at the end of you @PostConstruct [method]
[note that variables were NOT volatile]
I was thinking that happens-before is forced only if both write and read is executed in synchronized
block or at least read is volatile.
Is the quoted sentence correct? Does an empty synchronized(this) {}
block flush all variables changed in current method to "general visible" memory?
Please consider some scenerios
what if second thread never calls lock on
this
? (suppose that second thread reads in other methods). Remember that question is about: flush changes to other threads, not give other threads a way (synchronized) to poll changes made by original thread. Also no-synchronization in other methods is very likely in Spring@PostConstruct
context - as original comment says.is memory visibility of changes forced only in second and subsequent calls by another thread? (remember that this synchronized block is a last call in our method) - this would mark this way of synchronization as very bad practice (stale values in first call)