multithreading - java synchronized block for more than 1 objects? -
I have two arrays, and I need to synchronize access to them in threads. I'm putting them in a synchronized block. The problem is, I can pass only one of them to go to the 'Synchronized' St. One.
How do I ensure that access to both arrays is synchronized? Did I put them in a class and make a purpose of it? Or do I use only other arrays in the synchronized block, and it takes care of synchronized access to it?
Thanks,
Whatever you do no Do this:
Synchronize (array1) {synchronize (array2) {// do stuff}}
Unless you are very careful By then it is likely to lead. If you do this approach, then you should ensure that you have an irreversible partial order on the objects - Google "Dining Philosophers" to discuss the loss.
What you actually have to do is a lock object that you want to access if you want to access the either array and then use the all array access If you want to do this, it will be safe on thick grains. You can do it like this:
public stable class duarez {private int [] array1 = ... private int [ ] Array2 = ... private finals object lock = new object (); Public Zero doUpdate () {synchronize (LOCK) {...}}}
If you need a fisher-based method, then you need Java 5+ concurrent utilities such as But it would be more complicated to implement and error-prone.
Comments
Post a Comment