001package arez;
002
003import grim.annotations.OmitSymbol;
004import java.util.Objects;
005import javax.annotation.Nonnull;
006import javax.annotation.Nullable;
007import static org.realityforge.braincheck.Guards.*;
008
009/**
010 * A lock that stops the scheduler from running tasks until the lock is released.
011 */
012public final class SchedulerLock
013  implements Disposable
014{
015  @OmitSymbol( unless = "arez.enable_zones" )
016  @Nullable
017  private final ArezContext _context;
018  /**
019   * True if already released.
020   */
021  private boolean _released;
022
023  SchedulerLock( @Nullable final ArezContext context )
024  {
025    if ( Arez.shouldCheckInvariants() )
026    {
027      invariant( () -> Arez.areZonesEnabled() || null == context,
028                 () -> "Arez-0174: SchedulerLock passed a context but Arez.areZonesEnabled() is false" );
029    }
030    _context = Arez.areZonesEnabled() ? Objects.requireNonNull( context ) : null;
031  }
032
033  @Override
034  public void dispose()
035  {
036    if ( isNotDisposed() )
037    {
038      _released = true;
039      getContext().releaseSchedulerLock();
040    }
041  }
042
043  @Override
044  public boolean isDisposed()
045  {
046    return _released;
047  }
048
049  @Nonnull
050  private ArezContext getContext()
051  {
052    return Arez.areZonesEnabled() ? Objects.requireNonNull( _context ) : Arez.context();
053  }
054}