Is it possible to pass over a synchronized block of code when another thread has the synchronized object under lock? If not, is there an alternative that can act in this way?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can replace the
synchronizedblock with thejava.util.concurrent.locks.ReentrantLockclass. This class provides very similar mutual exclusion features, but it also has the methodtryLock, which acquires the lock if it’s free, or returns false immediately if it’s taken.So you can have something like:
Code of thread 1:
And thread 2: