I just created a singleton method, and I would like to know what the function @synchronized() does, as I use it frequently, but do not know the meaning.
I just created a singleton method, and I would like to know what the
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.
It declares a critical section around the code block. In multithreaded code,
@synchronizedguarantees that only one thread can be executing that code in the block at any given time.If you aren’t aware of what it does, then your application probably isn’t multithreaded, and you probably don’t need to use it (especially if the singleton itself isn’t thread-safe).
Edit: Adding some more information that wasn’t in the original answer from 2011.
The
@synchronizeddirective prevents multiple threads from entering any region of code that is protected by a@synchronizeddirective referring to the same object. The object passed to the@synchronizeddirective is the object that is used as the “lock.” Two threads can be in the same protected region of code if a different object is used as the lock, and you can also guard two completely different regions of code using the same object as the lock.Also, if you happen to pass
nilas the lock object, no lock will be taken at all.