001package arez;
002
003import grim.annotations.OmitType;
004import javax.annotation.Nonnull;
005
006/**
007 * An isolated Arez context.
008 */
009@OmitType( unless = "arez.enable_zones" )
010public final class Zone
011{
012  /**
013   * The underlying context for zone.
014   */
015  private final ArezContext _context = new ArezContext( this );
016
017  /**
018   * Return the context for the zone.
019   *
020   * @return the context for the zone.
021   */
022  @Nonnull
023  public ArezContext getContext()
024  {
025    return _context;
026  }
027
028  /**
029   * Create a zone.
030   * Should only be done via {@link Arez} methods.
031   */
032  Zone()
033  {
034  }
035
036  public boolean isActive()
037  {
038    return Arez.currentZone() == this;
039  }
040
041  /**
042   * Run the specified function in the zone.
043   * Activate the zone on entry, deactivate on exit.
044   *
045   * @param <T>    The type of the value returned from function.
046   * @param action the function to execute.
047   * @return the value returned from function.
048   */
049  public <T> T safeRun( @Nonnull final SafeFunction<T> action )
050  {
051    Arez.activateZone( this );
052    try
053    {
054      return action.call();
055    }
056    finally
057    {
058      Arez.deactivateZone( this );
059    }
060  }
061
062  /**
063   * Run the specified function in the zone.
064   * Activate the zone on entry, deactivate on exit.
065   *
066   * @param <T>    The type of the value returned from function.
067   * @param action the function to execute.
068   * @return the value returned from function.
069   * @throws Throwable if the function throws an exception.
070   */
071  public <T> T run( @Nonnull final Function<T> action )
072    throws Throwable
073  {
074    Arez.activateZone( this );
075    try
076    {
077      return action.call();
078    }
079    finally
080    {
081      Arez.deactivateZone( this );
082    }
083  }
084
085  /**
086   * Run the specified procedure in the zone.
087   * Activate the zone on entry, deactivate on exit.
088   *
089   * @param action the procedure to execute.
090   */
091  public void safeRun( @Nonnull final SafeProcedure action )
092  {
093    Arez.activateZone( this );
094    try
095    {
096      action.call();
097    }
098    finally
099    {
100      Arez.deactivateZone( this );
101    }
102  }
103
104  /**
105   * Run the specified procedure in the zone.
106   * Activate the zone on entry, deactivate on exit.
107   *
108   * @param action the procedure to execute.
109   * @throws Throwable if the procedure throws an exception.
110   */
111  public void run( @Nonnull final Procedure action )
112    throws Throwable
113  {
114    Arez.activateZone( this );
115    try
116    {
117      action.call();
118    }
119    finally
120    {
121      Arez.deactivateZone( this );
122    }
123  }
124}