问题
I want to write a simple thread-safe arraylist which supports:
add(), remove(int i), insert(int i), update(int i), and get(int i)
One simple implementation is to add lock to the internal data structure(an object array for example), but it is not good enough because only one thread could access the list at a time.
Therefore my initial plan is to add lock to each data slot so that different threads could have access to elements in different indexes at the same time. The data structure will look like this:
class MyArrayList {
Lock listlock;
Lock[] locks;
Object[] array;
}
The locking should work as follows if there is no need to do resize():
- for get(int i), a thread needs to acquire locks[i].
- for insert(int i), a thread needs to acquire all locks[j] for j >= i, and listlock.
- for remove(int i), a thread needs to acquire all locks[j] for j >= i, and listlock.
- for add(), a thread needs to acquire listlock.
- for insert(), a thread needs to acquire locks[i].
My questions are:
- How to handle the locks when resizing while more objects are adding and I need to create a new larger array to hold all objects. It is annoying because some other threads may also wait for the locks to be released,
- Any better suggestions to implement such thread-safe arraylist?
回答1:
A simple approach would be to just use a read-write lock ([Reentrant]ReadWriteLock), so many threads could read concurrently, but once someone gets the write lock, nobody else can access the list.
Or you could do something somewhat similar to your idea: one read-write lock for each slot + a global ("structural") read-write lock + a variable to keep track of the j >= i cases. So:
- To access (read or write) anything, a thread needs at least the global read lock.
- Only threads trying to make structural changes (the ones that change the size) get the global write lock, but only to set an
int modifyingFromvariable indicating all positions from there on are "locked" (thej >= icases). After settingmodifyingFrom, you downgrade (see docs) from write to read lock, letting others access the list. - Any thread trying to do anything that isn't a structural change, once holding the global read lock, checks if what it wants to do conflicts with the current value of
modifyingFrom. If there's a conflict, sleep until the thread who has setmodifyingFromfinishes and notifies everybody who is waiting. This check must be synchronized (just usesynchronized (obj)on some object) so the structure-changing thread doesn't happen toobj.notify()before the conflicting thread callsobj.wait()and sleeps forever (holding the global read lock!). :( - You should either have a
boolean structuralChangeHappening = falseor setmodifyingFromto somex > <list size>when no structural changes are happening (then you can just check thati < modifyingFromtoget()orupdate()). A thread finishing a structural change setsmodifyingFromback to this value and here's where it has to synchronize to notify waiting threads. - A thread wanting to make a structural change when one is already happening will wait because it needs the global write lock and at least one thread has the global read lock. In fact, it will wait until nobody is accessing the list at all.
- A thread allocating a new (bigger... or smaller, if you had a trimToSize() or something) array would hold the global write lock during the entire operation.
I was tempted to think the global read-write lock wasn't really necessary, but the last two points justify it.
Some example cases:
- Some threads trying to
get(i)(each with it'si, unique or not): each one would get the global read lock, then theith read lock, then read the position, and nobody would wait at all. - The same case with additional threads trying to
update([index =] i, element): if there are no equalis, nobody will wait. Otherwise, only the thread writing or the threads reading the conflicting position will wait. - A thread
tstarts aninsert([index =] 5, element), and other threads try toget(i): Oncethas setmodifyingFrom = 5and released the global write lock, all threads reading get the global read lock, then checkmodifyingFrom. Those withi < modifyingFromjust get the (read) lock of the slot; the others wait until theinsert(5)finishes and notifies, then get the lock of the slot. - A thread starts an
add()and needs to allocate a new array: Once it gets the global write lock, nobody else can do anything until it has finished. - The size of the list is 7, a thread
t_acallsadd(element)and another threadt_gcallsget([index =] 7):- If
t_ahappens to get the global write lock first, it setsmodifyingFrom = 7, and once it has released the lock,t_ggets the global read lock, sees thatindex (= 7) >= modifyingFromand sleeps untilt_afinishes and notifies it. - If
t_ggets the global read lock first, it checks that7 < modifyingFrom(modifyingFrom > <list size> (== 7), 4th point before the examples), then throws an exception because7 >= <list size>after releasing the lock! Thent_ais able to get the global write lock and proceeds normally.
- If
Remembering that accesses to modifyingFrom must be synchronized.
You said you want only that five operations, but if you wanted an iterator, it could check if something changed by other means (not the iterator itself), like standard classes do.
Now, I don't know under which conditions exactly this would be better than other approaches. Also, consider that you may need more restrictions in a real application, because this should ensure only consistency: if you try to read and write the same position, the read can happen before or after the write. Maybe it would make sense to have methods like tryUpdate(int, E), that only does something if no conflicting structural changes are happening when the method is called, or tryUpdate(int, E, Predicate<ArrayList>), which only does its work if the list is in a state that satisfies the predicate (which should be defined carefully not to cause deadlocks).
Please let me know if I missed something. There may be lots of corner cases. :)
来源:https://stackoverflow.com/questions/46436946/implement-a-thread-safe-arraylist-in-java-by-locking