This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
The ReadWriteLocks concept is new for me and I'm trying to understand it to use it in my FileAccess class...
Every example I see in the internet show code using the ReadWriteLocks to get read or write lock, to read or write in just one instance variable (a list for example).
I'd like to use one ReadWriteLocks instance, to read or write in two variables... because every time I'm modifying one, I modify the other.
So between the lock() and unLock() methods, I'll read or write two things.. is that a poor programming practice? Do you guys think I would loose points because this could be a little confusing for another programmer to maintain the code?
Lucas cotta wrote:I'd like to use one ReadWriteLocks instance, to read or write in two variables... because every time I'm modifying one, I modify the other.
Well, all you have to do is : obtain read or write lock as per your requirement (i.e. simply call methods on object of java.util.concurrent.locks.ReadWriteLock). That's it. Just take care that the data you are modifying after getting the lock is not getting modified anywhere without getting the lock. i.e. if you want to update few variables/objects or a collection - say a list; and you want to ensure thread-safety, then do as mentioned above. Just make sure that whenever you are dealing with that list, you must get the lock first. There's no point in having code where one method is acquiring lock before updating data and other method is updating data without acquiring lock.
I'm not a guru in the new concurrency API, but just using some common sense.
You'll use 1 instance of ReadWriteLock and you'll lock for read or update as you need. It makes no difference if you need to modify 1 or 10 data members (which depends on each other): just lock for write, modify all your data members and unlock for write. That's how you are supposed to use it in my opinion. It's a complete other story when you have 10 data members which could be changed in a multi-threaded environment independently, then you'll need 10 different instances of ReadWriteLock.