Domanda

I need to use a condition variable in my code. Looking up the android API, I saw that the package android.os contained ConditionVariable. But I also found Condition under java.util.concurrent.locks.

The two classes seem to be designed for the same purpose.

Condition.await()  <-> ConditionVariable.block()
Condition.signal() <-> ConditionVariable.open()

Is there a difference I should be aware of?

È stato utile?

Soluzione

As described in the docs you linked, Condition can wake single Threads, instead of waking all waiting ones (signal vs signalAll).

ConditionVariable is state-based and thus allows keeping the condition open (in contrast to releasing all waiting threads at a single time, it is possible to not block threads at all using open and close).


So you should use Condition if

  • you need to be compatible to regular Java (for example in a Library used for a PC/Server/whatever application, too), as ConditionVariable is not available there.
  • you need to wake single threads
  • (my personal opinion) you're not needing the open phase of ConditionVariable, as a single call to signalAll is nicer to read than open directly followed by close.

while you should use ConditionVariable if

  • you have phases within your application where you do not need any blocking at all

Altri suggerimenti

Use Android ConditionVariable when its essentially a single use block().

Use Java Condition when you have a loop that waits on await()

The reason is that there is no thread-safe way for the waiter to block() and then close() (without using additional synchronization mechanisms).

See examples of ConditionVariable here.

See examples of Condition here.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top