Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
Re: [aspectj-users] How to introduce a really final member via ITD

2013/5/30 Ivan Topolnjak <ivantopo@xxxxxxxxx>
I'm trying to find a way to introduce a member in another type via ITD but making sure it is safe published. According to the Java Memory Model, all final fields are guaranteed to be safe published after the constructor execution ends and everything not final is not guaranteed to ever be seen by another threads, so if I don't want to make use of synchronization I better make sure my things are final.. For the use case I have in hand, I'm trying to make a Runnable keep some information from the thread in which it was created and make it available to the thread in which it will be later run, a stub of what I did is this:

The question on how to introduce real final fields might be valid (you can't, AFAIK), but you don't need it for your use case. Your Runnable's fields will be seen with the correct values by the executing thread even if they're not final.

If it weren't the case, most multi-threaded Java programs would not run as most fields are usually not final. Dependency injection other than through constructor arguments wouldn't (reliably) work in a webapp as it's usually multi-threaded, for example.

Being unmodifiable (except through reflection), final fields avoid the problem of publishing the modifications once the object is shared and mutated by multiple threads, but an object completely constructed before it's shared with another thread will be properly seen, whether its fields are final or not.

Frank

Back to the top