Class BlockingVariable<T>

java.lang.Object
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 Details

    • BlockingVariable

      public BlockingVariable()
      Same as BlockingVariable(1).
    • BlockingVariable

      public BlockingVariable​(double timeout)
      Instantiates a BlockingVariable with the specified timeout in seconds.
      Parameters:
      timeout - the timeout (in seconds) for calls to get().
    • BlockingVariable

      @Deprecated public BlockingVariable​(int timeout, TimeUnit unit)
      Deprecated.
      Instantiates a BlockingVariable with the specified timeout.
      Parameters:
      timeout - the timeout for calls to get().
      unit - the time unit
  • Method Details

    • getTimeout

      public double getTimeout()
      Returns the timeout (in seconds).
      Returns:
      the timeout (in seconds)
    • 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