I am going to parallelize some code with some global variables. I am going to use ReentrantReadWriteLock. Did I understand it right, that I need one own instance of ReentrantReadWriteLock per variable I want to make thread safe?
I mean, when I have two lists where every thread can attach an item and all threads are sometimes reading items from that lists. In that case I would implement something like:
private static String[] globalVariables = null;
private static String[] processedItems = null;
private final ReentrantReadWriteLock globalVariablesLock = new ReentrantReadWriteLock();
private final Lock globalVariablesEeadLock = globalVariablesLock .readLock();
private final Lock globalVariablesWriteLock = globalVariablesLock .writeLock();
private final ReentrantReadWriteLock processedItemsLock = new ReentrantReadWriteLock();
private final Lock processedItemsLockReadLock = processedItemsLock .readLock();
private final Lock processedItemsLockWriteLock = processedItemsLock .writeLock();
What if I have much more variables like databaseconnection(pool)s, loggers, further lists, etc.
Do I need to make a new ReentrantReadWriteLock or do I missing something? Samples on the internet only handles one variable.
Thanks in advance.
Yes, you should have one Lock
per thread-safe variable (arrays in your case). However, consider using
ArrayList<String> syncList = Collections.synchronizedList(new ArrayList<String>());
instead of arrays. It is usually way better when you delegate to the library (in this case, not only the synchronization but also the resize of the arrays). Of course, before doing it check that the library does exactly what you would expect (in this case, as @SashaSalauyou pointed out, you'd lose the ability to read concurrently).