I have a Data Transfer Object (DTO) in a Java application that is being read from and written to in several different threads across the application. Up until now I have been able to use synchronized(dto.class) for synchronization. There is now one instance where I need to hold the lock outside of the method that it is called in, so I will use the ReentrantLock() class.
Is there a thread safe way to use a reentrant lock for its functionality in the one instance while keeping the synchronized blocks as is in the rest of the code? Or, is it the case that the use of a reentrant lock means all related synchronized blocks have to be removed?
What data do the
synchronizedblocks protect? What data do you want to protect with theReentrantLock? If they're different data then there should be no problem using different means to protect them. But it doesn't make any sense to usesynchronizedin one place andReentrantLockin a different place if you're trying to protect the same data in both places. Locking aReentrantLockwill not prevent some other thread from entering asynchronizedblock and vice versa.