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 a Lock
implementation as you cannot instantiate interfaces.
As per the docs
You have 3 choices:
Condition
s are bound to Lock
s.You're probably looking for the ReentrantLock
possibly with some Condition
s
This means that instead of Lock l = new Lock();
you would do:
ReentrantLock lock = new ReentrantLock();
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:
public synchronized void setValue (var newValue)
{
value = newValue;
}
or if this is a part of a larger method:
public void doInfinite ()
{
//code
synchronized (this)
{
value = aValue;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With