<commit_before>package io.futures;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;

public class Promise<T> implements Future<T> {

  private static final long stateOffset = Unsafe.objectFieldOffset(Promise.class, "state");

  // Future<T> (Done) | Promise<T> (Linked) | WaitQueue|Null (Pending)
  private Object state;

  private InterruptHandler interruptHandler;

  private final Optional<?>[] savedContext = Local.save();

  public Promise() {
    super();
  }

  public Promise(final InterruptHandler interruptHandler) {
    super();
    this.interruptHandler = interruptHandler;
  }

  public Promise(final List<? extends InterruptHandler> interruptHandlers) {
    super();
    this.interruptHandler = (ex) -> {
      for (final InterruptHandler handler : interruptHandlers)
        handler.raise(ex);
    };
  }

  private final boolean cas(final Object oldState, final Object newState) {
    return Unsafe.compareAndSwapObject(this, stateOffset, oldState, newState);
  }

  public final void become(final Future<T> result) {
    if (!becomeIfEmpty(result))
      throw new IllegalStateException("Can't set result " + result + " for promise with state " + state);
  }

  @SuppressWarnings("unchecked")
  public final boolean becomeIfEmpty(final Future<T> result) {
    try {
      while (true) {
        final Object curr = state;
        if (curr instanceof SatisfiedFuture)
          return false;
        else if (curr instanceof Promise && !(curr instanceof Continuation))
          return ((Promise<T>) curr).becomeIfEmpty(result);
        else if (result instanceof Promise) {
          ((Promise<T>) result).compress().link(this);
          return true;
        } else if (cas(curr, result)) {
          flush((WaitQueue<T>) curr, result);
          return true;
        }
      }
    } catch (final StackOverflowError ex) {
      System.err.println(
          "FATAL: Stack overflow when satisfying promise. Use `Future.tailrec` or increase the stack size (-Xss).");
      throw ex;
    }
  }

  private final void flush(final WaitQueue<T> queue, final Future<T> result) {
    if (queue == null)
      return;
    else {
      final Optional<?>[] oldContext = Local.save();
      Local.restore(savedContext);
      try {
        queue.flush(result);
      } finally {
        Local.restore(oldContext);
      }
    }
  }

  @SuppressWarnings("unchecked")
  private final void link(final Promise<T> target) {
    while (true) {
      final Object curr = state;
      if (curr instanceof SatisfiedFuture) {
        target.become((SatisfiedFuture<T>) curr);
        return;
      } else if (cas(curr, target)) {
        if (curr != null)
          ((WaitQueue<T>) curr).forward(target);
        return;
      }
    }
  }

  @SuppressWarnings("unchecked")
  protected final <R> Future<R> continuation(final Continuation<T, R> c) {
    while (true) {
      final Object curr = state;
      if (curr instanceof SatisfiedFuture) {
        c.flush((SatisfiedFuture<T>) curr);
        return c;
      } else if (curr instanceof Promise && !(curr instanceof Continuation))
        return ((Promise<T>) curr).continuation(c);
      else if (curr == null && cas(curr, c))
        return c;
      else if (curr != null && cas(curr, ((WaitQueue<T>) curr).add(c)))
        return c;
    }
  }

  @SuppressWarnings("unchecked")
  private final Promise<T> compress() {
    while (true) {
      final Object curr = state;
      if (curr instanceof Promise && !(curr instanceof Continuation)) { // Linked
        final Promise<T> target = ((Promise<T>) curr).compress();
        if (cas(curr, target))
          return target;
      } else
        return this;
    }
  }

  public final void setValue(final T value) {
    become(new ValueFuture<>(value));<commit_msg>optimizations<commit_after>package io.futures;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;

public class Promise<T> implements Future<T> {

  private static final long stateOffset = Unsafe.objectFieldOffset(Promise.class, "state");

  // Future<T> (Done) | Promise<T> (Linked) | WaitQueue|Null (Pending)
  private Object state;

  private InterruptHandler interruptHandler;

  private final Optional<?>[] savedContext = Local.save();

  public Promise() {
  }

  public Promise(final InterruptHandler interruptHandler) {
    this.interruptHandler = interruptHandler;
  }

  public Promise(final List<? extends InterruptHandler> interruptHandlers) {
    this.interruptHandler = (ex) -> {
      for (final InterruptHandler handler : interruptHandlers)
        handler.raise(ex);
    };
  }

  private final boolean cas(final Object oldState, final Object newState) {
    return Unsafe.compareAndSwapObject(this, stateOffset, oldState, newState);
  }

  public final void become(final Future<T> result) {
    if (!becomeIfEmpty(result))
      throw new IllegalStateException("Can't set result " + result + " for promise with state " + state);
  }

  @SuppressWarnings("unchecked")
  public final boolean becomeIfEmpty(final Future<T> result) {
    try {
      while (true) {
        final Object curr = state;
        if (curr instanceof SatisfiedFuture)
          return false;
        else if (curr instanceof Promise && !(curr instanceof Continuation))
          return ((Promise<T>) curr).becomeIfEmpty(result);
        else if (result instanceof Promise) {
          ((Promise<T>) result).compress().link(this);
          return true;
        } else if (cas(curr, result)) {
          if (curr != null)
            flush((WaitQueue<T>) curr, result);
          return true;
        }
      }
    } catch (final StackOverflowError ex) {
      System.err.println(
          "FATAL: Stack overflow when satisfying promise. Use `Future.tailrec` or increase the stack size (-Xss).");
      throw ex;
    }
  }

  private final void flush(final WaitQueue<T> queue, final Future<T> result) {
    final Optional<?>[] oldContext = Local.save();
    Local.restore(savedContext);
    try {
      queue.flush(result);
    } finally {
      Local.restore(oldContext);
    }
  }

  @SuppressWarnings("unchecked")
  private final void link(final Promise<T> target) {
    while (true) {
      final Object curr = state;
      if (curr instanceof SatisfiedFuture) {
        target.become((SatisfiedFuture<T>) curr);
        return;
      } else if (cas(curr, target)) {
        if (curr != null)
          ((WaitQueue<T>) curr).forward(target);
        return;
      }
    }
  }

  @SuppressWarnings("unchecked")
  protected final <R> Future<R> continuation(final Continuation<T, R> c) {
    while (true) {
      final Object curr = state;
      if (curr instanceof SatisfiedFuture) {
        c.flush((SatisfiedFuture<T>) curr);
        return c;
      } else if (curr instanceof Promise && !(curr instanceof Continuation)) {
        return ((Promise<T>) curr).continuation(c);
      } else if (curr == null) {
        if (cas(curr, c))
          return c;
      } else if (curr != null) {
        if (cas(curr, ((WaitQueue<T>) curr).add(c)))
          return c;
      }
    }
  }

  @SuppressWarnings("unchecked")
  private final Promise<T> compress() {
    while (true) {
      final Object curr = state;
      if (curr instanceof Promise && !(curr instanceof Continuation)) { // Linked
        final Promise<T> target = ((Promise<T>) curr).compress();
        if (cas(curr, target))
          return target;
      } else
        return this;
    }
  }

  public final void setValue(final T value) {
    become(new ValueFuture<>(value));
{'fraction_non_alphanumeric': 0.11907414283946033, 'fraction_numerical': 0.0, 'mean_word_length': 2.9530332681017613, 'pattern_counts': {'":': 0, '<': 57, '<?xml version=': 0, '>': 59, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4538703', 'n_tokens_mistral': 2295, 'n_tokens_neox': 2304, 'n_words': 638}