Embed a thread safe ArrayList in Java by locking

I want to write a simple thread safe arraylist that supports:

add (), remove (int i), insert (int i), update (int i) and get (int i)

One simple implementation is to add a lock to the internal data structure (for example, an array of objects), but this is not enough because only one thread could access the list at a time.

So my initial plan was to add a lock to each data slot, so that different threads can simultaneously access elements in different indexes. The data structure will look like this:

class MyArrayList {
    Lock listlock;
    Lock[] locks;
    Object[] array;
}

The lock should work as follows if there is no need to resize ():

  • for get (int i), the thread must get locks [i].
  • to insert (int i) the thread must get all the locks [j] for j> = i and listlock.
  • to delete (int i), the thread must get all the locks [j] for j> = i and listlock.
  • for add (), the stream should receive listlock.
  • for insert (), the thread must get locks [i].

My questions:

  • How to handle locks when resizing when adding more objects, and I need to create a new larger array to store all objects. This is annoying because some other threads may also wait for the locks to be released,
  • Any best suggestions for introducing such a thread safe arraylist?
+4
source share
1 answer

([Reentrant]ReadWriteLock), , - , .

- : - + ( "" ) + j >= i. :

  • ( ), .
  • , (, ), , int modifyingFrom, , "" ( j >= i), modifyingFrom (. docs) , .
  • , -, , , , modifyingFrom. , , , modifyingFrom, , . ( synchronized (obj) - ), obj.notify() , obj.wait() ( !).: (
  • boolean structuralChangeHappening = false, modifyingFrom x > <list size>, ( , i < modifyingFrom - get() update()). , , modifyingFrom , .
  • , , , , , . , , .
  • , (... , trimToSize() - ), .

, , .

:

  • get(i) ( i, ): , i th , , .
  • , update([index =] i, element): i s, . , .
  • t insert([index =] 5, element), get(i): t modifyingFrom = 5 , , modifyingFrom. , i < modifyingFrom, () ; , insert(5) , .
  • add() : , , , .
  • 7, t_a add(element), t_g get([index =] 7):
    • t_a , modifyingFrom = 7, , , t_g , , index (= 7) >= modifyingFrom t_a .
    • t_g , , 7 < modifyingFrom (modifyingFrom > <list size> (== 7), 4- ), , 7 >= <list size> ! t_a .

, modifyingFrom .

, , , , - ( ), .

, , . , , : , . , , tryUpdate(int, E), -, tryUpdate(int, E, Predicate<ArrayList>), , , ( , ).

, , - . .:)

0

Source: https://habr.com/ru/post/1686444/


All Articles