I got asked the following question in an interview while talking about concurrency in Java. I couldnt come up with a good strategy. Any ideas?
How do you share access to a resource in java without synchronizing the code?
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.
If the resource is immutable then no synchronization is needed, but barring that, here are a few ideas:
Restrict all access to read-only: if nothing is updating the resource then any number of concurrent threads can safely have read access to it.
Copy the resource per subscriber: any number of threads can have their own copy of a resource and safely modify it with no impact on other threads with their own copy. (e.g.
ThreadLocal)Use an atomic reference to emulate synchronization: a “getter” method use check an atomic reference (e.g.
AtomicBoolean) to create a “check in” / “check out” system to ensure that only one thread has access to the resource, no synchronization needed.Use a lock from
java.util.concurrent.locks: which can provide the same (or even better) functionality without using thesynchronizedkeyword.Of course, the interviewer might impose additional restrictions but these are good starting points given the little information in your question.