Reputation: 93
I am learning multithreading, and I have a little question. When I am sharing some variable between threads (ArrayList, or something other like double, float), should it be lcoked by the same object in read/write? I mean, when 1 thread is setting variable value, can another read at same time withoud any problems? Or should it be locked by same object, and force thread to wait with reading, until its changed by another thread?
Upvotes: 0
Views: 140
Reputation: 8819
If all threads are reading, you do not need to synchronize.
If one or more threads are reading and one or more are writing you will need to synchronize somehow. If the collection is small you can use synchronized
. You can either add a synchronized
block around the accesses to the collection, synchronized
the methods that access the collection or use a concurrent threadsafe collection (for example, Vector).
If you have a large collection and you want to allow shared reading but exclusive writing you need to use a ReadWriteLock
. See here for the JavaDoc and an exact description of what you want with examples:
Note that this question is pretty common and there are plenty of similar examples on this site.
Upvotes: 0
Reputation: 24747
Short: It depends.
Longer: There is many "correct answer" for each different scenarios. (and that makes programming fun)
tl;dr
For example, not all threaded programming need "always correct"
Here is my suggestion: If you are learning, you should thing "why should I need a lock?" and "why a lock can help in DIFFERENT cases?" (not just the given sample from textbook), "will if fail or what could happen if a lock is missing?"
Upvotes: 0
Reputation: 200138
All access to shared state must be guarded by the same lock, both reads and writes. A read operation must wait for the write operation to release the lock.
As a special case, if all you would to inside your synchronized blocks amounts to exactly one read or write operation, then you may dispense with the synchronized block and mark the variable as volatile.
Upvotes: 1