This must be really obvious, but I can’t spot the answer. I need to put a lock around a variable to ensure that a couple of race-hazard conditions are avoided. From what I can see, a pretty simple solution exists using Lock, according to the android docs:
Lock l = ...;
l.lock();
try {
// access the resource protected by this lock
}
finally {
l.unlock();
}
So far, so good. However, I can’t make the first line work. It would seem that something like:
Lock l = new Lock();
Might be correct, but eclipse reports, “Cannot instantiate the type Lock” – and no more.
Any suggestions?
If you’re very keen on using a
Lock, you need to choose aLockimplementation as you cannot instantiate interfaces.As per the docs
You have 3 choices:
Conditions are bound toLocks.You’re probably looking for the
ReentrantLockpossibly with someConditionsThis means that instead of
Lock l = new Lock();you would do:However, if all you’re needing to lock is a small part, a synchronized block/method is cleaner (as suggested by @Leonidos & @assylias).
If you have a method that sets the value, you can do:
or if this is a part of a larger method: