This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I have a scenario where there is an object let's say context which needs to be passed from threadA to the the other thread say threadB..
As soon as the object is passed to threadB ...threadA returns back and starts making changes to context object ..but it might happen
that threadB hasn't done it work so the value of context would have been changed..there is a problem
My question is how can we deal with this..
One scenario I can think of passing is that I would pass a cloned object of the context rather than the context itself to the ThreadB..
But let's assume it's not a option..
Also how would syncronisation work here....I can get a lock on the context itself but it still doesn't solve the problem
because it might happen threadA will get the lock and modify the context object..
1. Do not hand over context to threadB until threadA's changes to context are complete.
2. Hand over context to threadB if it is only going to 'use' the context and not 'modify' it. If this is the case then please have a look at java.util.concurrent.locks.ReentrantReadWriteLock Word of caution: Since threadB can use the context while threadA is modifying it, make sure that threadB's code is not dependent on those changes. Why? because they may or may not happen by the time threadB tries to use the context.
If both threadA and threadB are going to 'modify' the context then one needs to understand what those modifications are. Modifications are to the context object itself or to the object's maintained by the context (its not clear as to what context we are talking about).
If modifications are to the context itself then you dont have any other option than locking it. Depending on 'context' code (William's question #2) you can use synchronized() or a lock.
If modifications are to the objects maintained by the context, then you can look into locking those objects instead of context.