Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Lock (concurrent.locks.Lock) in Android?

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?

like image 732
Neil Townsend Avatar asked Jan 06 '13 21:01

Neil Townsend


1 Answers

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:

  • ReentrantLock
  • Condition This isn't a Lock itself but rather a helper class since Conditions are bound to Locks.
  • ReadWriteLock

You're probably looking for the ReentrantLock possibly with some Conditions

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;
  }
}
like image 198
A--C Avatar answered Sep 22 '22 23:09

A--C