001// Copyright (c) FIRST and other WPILib contributors.
002// Open Source Software; you can modify and/or share it under the terms of
003// the WPILib BSD license file in the root directory of this project.
004
005package edu.wpi.first.util.concurrent;
006
007import edu.wpi.first.util.WPIUtilJNI;
008
009/**
010 * An atomic signaling event for synchronization.
011 *
012 * <p>Events have binary state (signaled or not signaled) and may be either automatically reset or
013 * manually reset. Automatic-reset events go to non-signaled state when a waitForObject is woken up
014 * by the event; manual-reset events require reset() to be called to set the event to non-signaled
015 * state; if reset() is not called, any waiter on that event will immediately wake when called.
016 */
017public final class Event implements AutoCloseable {
018  /**
019   * Constructor.
020   *
021   * @param manualReset true for manual reset, false for automatic reset
022   * @param initialState true to make the event initially in signaled state
023   */
024  public Event(boolean manualReset, boolean initialState) {
025    m_handle = WPIUtilJNI.createEvent(manualReset, initialState);
026  }
027
028  /**
029   * Constructor. Initial state is false.
030   *
031   * @param manualReset true for manual reset, false for automatic reset
032   */
033  public Event(boolean manualReset) {
034    this(manualReset, false);
035  }
036
037  /** Constructor. Automatic reset, initial state is false. */
038  public Event() {
039    this(false, false);
040  }
041
042  @Override
043  public void close() {
044    if (m_handle != 0) {
045      WPIUtilJNI.destroyEvent(m_handle);
046      m_handle = 0;
047    }
048  }
049
050  /**
051   * Gets the event handle (e.g. for waitForObject).
052   *
053   * @return handle
054   */
055  public int getHandle() {
056    return m_handle;
057  }
058
059  /** Sets the event to signaled state. */
060  public void set() {
061    WPIUtilJNI.setEvent(m_handle);
062  }
063
064  /** Sets the event to non-signaled state. */
065  public void reset() {
066    WPIUtilJNI.resetEvent(m_handle);
067  }
068
069  private int m_handle;
070}