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?