spock.util.concurrent
Class BlockingVariable<T>

java.lang.Object
  extended by spock.util.concurrent.BlockingVariable<T>
Type Parameters:
T - the variable's type

public class BlockingVariable<T>
extends Object

A statically typed variable whose get() method will block until some other thread has set a value with the set() method, or a timeout expires. Useful for verifying state in an expect- or then-block that has been captured in some other thread.

Example:

 // create object under specification
 def machine = new Machine()

 def result = new BlockingVariable<WorkResult>

 // register async callback
 machine.workDone << { r ->
  result.set(r)
 }

 when:
 machine.start()

 then:
 // blocks until workDone callback has set result, or a timeout expires
 result.get() == WorkResult.OK

 cleanup:
 // shut down all threads
 machine?.shutdown()
 


Constructor Summary
BlockingVariable()
          Same as BlockingVariable(1, TimeUnit.SECONDS).
BlockingVariable(int timeout)
          Instantiates a BlockingVariable with the specified timeout in seconds.
BlockingVariable(int timeout, TimeUnit unit)
          Instantiates a BlockingVariable with the specified timeout.
 
Method Summary
 T get()
          Blocks until a value has been set for this variable, or a timeout expires.
 void set(T value)
          Sets a value for this variable.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

BlockingVariable

public BlockingVariable()
Same as BlockingVariable(1, TimeUnit.SECONDS).


BlockingVariable

public BlockingVariable(int timeout)
Instantiates a BlockingVariable with the specified timeout in seconds.

Parameters:
timeout - the timeout (seconds) for calls to get().

BlockingVariable

public BlockingVariable(int timeout,
                        TimeUnit unit)
Instantiates a BlockingVariable with the specified timeout.

Parameters:
timeout - the timeout for calls to get().
unit - the time unit
Method Detail

get

public T get()
      throws InterruptedException
Blocks until a value has been set for this variable, or a timeout expires.

Returns:
the variable's value
Throws:
InterruptedException - if the calling thread is interrupted

set

public void set(T value)
Sets a value for this variable. Wakes up all threads blocked in get().

Parameters:
value - the value to be set for this variable