<commit_before>package io.futures;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;

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

  private static final long STATE_OFFSET = Unsafe.objectFieldOffset(Promise.class, "state");
  private static final Logger LOGGER = Logger.getLogger(Promise.class.getName());

  public static final <T> Promise<T> apply(final List<? extends InterruptHandler> handlers) {
    final Optional<?>[] savedContext = Local.save();
    return new Promise<T>() {
      @Override
      protected final Optional<?>[] getSavedContext() {
        return savedContext;
      }

      @Override
      protected final InterruptHandler getInterruptHandler() {
        return InterruptHandler.apply(handlers);
      }
    };
  }

  public static final <T> Promise<T> apply(final InterruptHandler h1, final InterruptHandler h2) {
    final Optional<?>[] savedContext = Local.save();
    return new Promise<T>() {
      @Override
      protected final Optional<?>[] getSavedContext() {
        return savedContext;
      }

      @Override
      protected final InterruptHandler getInterruptHandler() {
        return InterruptHandler.apply(h1, h2);
      }
    };
  }

  public static final <T> Promise<T> apply(final InterruptHandler handler) {
    final Optional<?>[] savedContext = Local.save();
    return new Promise<T>() {
      @Override
      protected final Optional<?>[] getSavedContext() {
        return savedContext;
      }

      @Override
      protected final InterruptHandler getInterruptHandler() {
        return handler;
      }
    };
  }

  public static final <T> Promise<T> apply() {
    final Optional<?>[] savedContext = Local.save();
    return new Promise<T>() {
      @Override
      protected final Optional<?>[] getSavedContext() {
        return savedContext;
      }
    };
  }

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

  protected InterruptHandler getInterruptHandler() {
    return null;
  }

  protected Optional<?>[] getSavedContext() {
    return null;
  }

  private final boolean cas(final Object oldState, final Object newState) {
    return Unsafe.compareAndSwapObject(this, STATE_OFFSET, 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 (curr instanceof LinkedContinuation)
          return ((LinkedContinuation<?, 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) {
      LOGGER.log(Level.SEVERE,
          "FATAL: Stack overflow when satisfying promise, the promise and its continuations won't be satisfied. "
              + "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<?>[] savedContext = getSavedContext();
    Optional<?>[] originalContext;
    if (savedContext != null && (originalContext = Local.save()) != savedContext) {
      Local.restore(savedContext);
      try {
        queue.flush(result);
      } finally {
        Local.restore(originalContext);
      }
    } else
      queue.flush(result);
  }

  @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 (target instanceof Continuation) {
        if (cas(curr, new LinkedContinuation<>((Continuation<T, ?>) target)))
          return;
      } else if (cas(curr, target)) {<commit_msg>better logging for stack overflows<commit_after>package io.futures;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;

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

  private static final long STATE_OFFSET = Unsafe.objectFieldOffset(Promise.class, "state");
  private static final Logger LOGGER = Logger.getLogger(Promise.class.getName());

  public static final <T> Promise<T> apply(final List<? extends InterruptHandler> handlers) {
    final Optional<?>[] savedContext = Local.save();
    return new Promise<T>() {
      @Override
      protected final Optional<?>[] getSavedContext() {
        return savedContext;
      }

      @Override
      protected final InterruptHandler getInterruptHandler() {
        return InterruptHandler.apply(handlers);
      }
    };
  }

  public static final <T> Promise<T> apply(final InterruptHandler h1, final InterruptHandler h2) {
    final Optional<?>[] savedContext = Local.save();
    return new Promise<T>() {
      @Override
      protected final Optional<?>[] getSavedContext() {
        return savedContext;
      }

      @Override
      protected final InterruptHandler getInterruptHandler() {
        return InterruptHandler.apply(h1, h2);
      }
    };
  }

  public static final <T> Promise<T> apply(final InterruptHandler handler) {
    final Optional<?>[] savedContext = Local.save();
    return new Promise<T>() {
      @Override
      protected final Optional<?>[] getSavedContext() {
        return savedContext;
      }

      @Override
      protected final InterruptHandler getInterruptHandler() {
        return handler;
      }
    };
  }

  public static final <T> Promise<T> apply() {
    final Optional<?>[] savedContext = Local.save();
    return new Promise<T>() {
      @Override
      protected final Optional<?>[] getSavedContext() {
        return savedContext;
      }
    };
  }

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

  protected InterruptHandler getInterruptHandler() {
    return null;
  }

  protected Optional<?>[] getSavedContext() {
    return null;
  }

  private final boolean cas(final Object oldState, final Object newState) {
    return Unsafe.compareAndSwapObject(this, STATE_OFFSET, 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 (curr instanceof LinkedContinuation)
          return ((LinkedContinuation<?, 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) {
      if (!(this instanceof Continuation))
        LOGGER.log(Level.SEVERE,
            "FATAL: Stack overflow when satisfying promise, the promise and its continuations won't be satisfied. "
                + "Use `Future.tailrec` or increase the stack size (-Xss).", ex);
      throw ex;
    }
  }

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

  @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 (target instanceof Continuation) {
        if (cas(curr, new LinkedContinuation<>((Continuation<T, ?>) target)))
          return;
      } else if (cas(curr, target)) {
{'fraction_non_alphanumeric': 0.11434511434511435, 'fraction_numerical': 0.0008316008316008316, 'mean_word_length': 3.083616298811545, 'pattern_counts': {'":': 0, '<': 85, '<?xml version=': 0, '>': 85, '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': '2395887', 'n_tokens_mistral': 2652, 'n_tokens_neox': 2634, 'n_words': 733}