Reputation: 351
Say I have some vectors: v1, v2, v3
Say I also have a vector that holds these vList = {v1, v2, v3}
If I synchronized (vList), does this mean that v1, v2, and v3 are also locked or does it just lock vList?
Upvotes: 1
Views: 805
Reputation: 2875
Synchronized doesn't lock objects! It marks a critical section of code.
If you use it for a method (synchronized void foo()
) only one Thread can access this method.
If you use it with an object (synchronized(bar)
) only a thread owing the lock on this object can enter the critical zone.
This means synchronizing on 'bar' requires every thread that wants to enter this zone (or any other synced on 'bar') to request the lock. If they don't acquire it they are blocked until the Thread owning the lock releases it.
This means if all your vectors are only worked with in a block synchronized on one variable this is usually enough.
Syncing in multiple objects in a row is also no problem:
synchronized(bar){..} synchronized(foo){..}
Where it gets tricky is cascaded syncs as this may lead to deadlocks:
synchronized(bar){
synchronized(foo){..}
}
And last but not least:
You wont have to lock a Vector to make it threadsave as each method of vector is defined with synchronized
(As seen here). You only have to set up an additional lock if you want to edit multiple Vectors without interference from other Threads.
Upvotes: 1
Reputation: 182819
It's up to you to decide what the lock protects. If you decide it locks all three of them, then it locks all three of them. Just reflect that decision in all the code that accesses those objects.
The relationship between locks and objects is a code design concept that must be reflected in all the code that deals with the locked objects. To avoid race conditions and other bugs, programmers can use a lock to protect an object. We say lock "X" locks object "Y" if we intend that all accesses to object "Y" are performed while holding lock "X". Since only one thread can hold lock "X" at time, this rule ensures that only one thread at a time accesses object "Y". The lock does not know or care what object(s) it protects.
If all code that accesses "v1" holds the "vList" lock when it accesses it, then "vList" locks "v1". If there's some code that accesses "v1" without holding the "vList" lock, the "vList" does not lock "v1".
Upvotes: 3
Reputation: 726809
Each Vector<T>
is making only its own content thread-safe:
Vector<Vector<T>>
is locking the vector of vectors, but not the individual vectorsVector<T>
inside it is locking the vector of T
itself.In other words, if you get two vectors of T
from inside your vector of vectors, and give these vectors to different threads, you would be able to access the vectors simultaneously, without the threads locking out each other.
On the other hand, if you start accessing the vector of vectors concurrently, the accesses would be mutually exclusive, because the vector is synchronized.
Upvotes: 1