jlaufer
jlaufer

Reputation: 177

Can a reentrant lock work in conjunction with a synchronized block?

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?

Upvotes: 0

Views: 133

Answers (1)

Solomon Slow
Solomon Slow

Reputation: 27190

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?

What data do the synchronized blocks protect? What data do you want to protect with the ReentrantLock? 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 use synchronized in one place and ReentrantLock in a different place if you're trying to protect the same data in both places. Locking a ReentrantLock will not prevent some other thread from entering a synchronized block and vice versa.

Upvotes: 0

Related Questions