/**
   * Constructs a new, empty set that orders its elements according to the specified comparator.
   *
   * @param max Upper bound of this map.
   * @param comparator The comparator that will be used to order this map. If <tt>null</tt>, the
   *     {@linkplain Comparable natural ordering} of the elements will be used.
   */
  public GridBoundedConcurrentOrderedMap(int max, Comparator<? super K> comparator) {
    super(comparator);

    A.ensure(max > 0, "max > 0");

    this.max = max;
  }
  /**
   * Constructs a new map containing the same elements and using the same ordering as the specified
   * sorted map.
   *
   * @param max Upper bound of this map.
   * @param map Sorted map whose elements will comprise the new map.
   * @throws NullPointerException if the specified sorted map or any of its elements are {@code
   *     null}.
   */
  public GridBoundedConcurrentOrderedMap(int max, SortedMap<K, V> map) {
    super(map);

    A.ensure(max > 0, "max > 0");

    this.max = max;
  }
  /**
   * Constructs a new map containing the elements in the specified map, that orders its elements
   * according to their {@linkplain Comparable natural ordering}.
   *
   * @param max Upper bound of this map.
   * @param map The elements that will comprise the new map.
   * @throws ClassCastException if the elements in <tt>map</tt> are not {@link Comparable}, or are
   *     not mutually comparable.
   * @throws NullPointerException if the specified map or any of its elements are {@code null}.
   */
  public GridBoundedConcurrentOrderedMap(int max, Map<? extends K, ? extends V> map) {
    super(map);

    A.ensure(max > 0, "max > 0");

    this.max = max;
  }
Beispiel #4
0
  /**
   * Gets option value. If this option is "none" this method will throw {@link
   * IllegalArgumentException} exception. Note that this method may return {@code null}.
   *
   * @return An option value.
   * @throws IllegalArgumentException Thrown in case if this option is "none".
   */
  public T get() {
    A.ensure(this != NONE, "Value 'none' of GridOpt cannot be used.");

    assert val != null;

    return val;
  }
  /** {@inheritDoc} */
  @Override
  public CacheQuery<T> timeout(long timeout) {
    A.ensure(timeout >= 0, "timeout >= 0");

    this.timeout = timeout;

    return this;
  }
  /** {@inheritDoc} */
  @Override
  public CacheQuery<T> pageSize(int pageSize) {
    A.ensure(pageSize > 0, "pageSize > 0");

    this.pageSize = pageSize;

    return this;
  }
  /**
   * Set local batch size for this sequences.
   *
   * @param size Sequence batch size. Must be more then 0.
   */
  @Override
  public void batchSize(int size) {
    A.ensure(size > 0, " Batch size can't be less then 0: " + size);

    lock.lock();

    try {
      batchSize = size;
    } finally {
      lock.unlock();
    }
  }
  /** {@inheritDoc} */
  @Override
  public void saveCheckpoint(
      String key, Object state, GridTaskSessionScope scope, long timeout, boolean overwrite)
      throws GridException {
    A.notNull(key, "key");
    A.ensure(timeout >= 0, "timeout >= 0");

    synchronized (mux) {
      if (closed) throw new GridException("Failed to save checkpoint (session closed): " + this);
    }

    ctx.checkpoint().storeCheckpoint(this, key, state, scope, timeout, overwrite);
  }
  /** {@inheritDoc} */
  @Override
  public void autoFlushFrequency(long autoFlushFreq) {
    A.ensure(autoFlushFreq >= 0, "autoFlushFreq >= 0");

    long old = this.autoFlushFreq;

    if (autoFlushFreq != old) {
      this.autoFlushFreq = autoFlushFreq;

      if (autoFlushFreq != 0 && old == 0) flushQ.add(this);
      else if (autoFlushFreq == 0) flushQ.remove(this);
    }
  }
  /** {@inheritDoc} */
  @Override
  public void bufferSize(int bufSize) {
    A.ensure(bufSize > 0, "bufSize > 0");

    if (!guard.enterBusy())
      throw new IllegalStateException("Continuous query can't be changed after it was executed.");

    try {
      this.bufSize = bufSize;
    } finally {
      guard.leaveBusy();
    }
  }
  /** {@inheritDoc} */
  @Override
  public void timeInterval(long timeInterval) {
    A.ensure(timeInterval >= 0, "timeInterval >= 0");

    if (!guard.enterBusy())
      throw new IllegalStateException("Continuous query can't be changed after it was executed.");

    try {
      this.timeInterval = timeInterval;
    } finally {
      guard.leaveBusy();
    }
  }
  /** {@inheritDoc} */
  @Override
  public R get(long timeout, TimeUnit unit) throws IgniteCheckedException {
    A.ensure(timeout >= 0, "timeout cannot be negative: " + timeout);
    A.notNull(unit, "unit");

    try {
      return get0(unit.toNanos(timeout));
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();

      throw new IgniteInterruptedCheckedException(
          "Got interrupted while waiting for future to complete.", e);
    }
  }
  /** {@inheritDoc} */
  @Override
  public R get(long timeout, TimeUnit unit) throws GridException {
    A.ensure(timeout >= 0, "timeout cannot be negative: " + timeout);
    A.notNull(unit, "unit");

    checkValid();

    try {
      long now = System.currentTimeMillis();

      long end = timeout == 0 ? Long.MAX_VALUE : now + MILLISECONDS.convert(timeout, unit);

      // Account for overflow.
      if (end < 0) end = Long.MAX_VALUE;

      synchronized (mux) {
        while (!done && !cancelled && now < end) {
          mux.wait(end - now);

          if (!done) now = System.currentTimeMillis();
        }

        if (done) {
          if (err != null) throw U.cast(err);

          return res;
        }

        if (cancelled) throw new GridFutureCancelledException("Future was cancelled: " + this);

        throw new GridFutureTimeoutException(
            "Timeout was reached before computation completed [duration="
                + duration()
                + "ms, timeout="
                + unit.toMillis(timeout)
                + "ms]");
      }
    } catch (InterruptedException e) {
      throw new GridInterruptedException(
          "Got interrupted while waiting for future to complete [duration="
              + duration()
              + "ms, timeout="
              + unit.toMillis(timeout)
              + "ms]",
          e);
    }
  }
  /**
   * Sets maximum allowed size of cache before entry will start getting evicted.
   *
   * @param max Maximum allowed size of cache before entry will start getting evicted.
   */
  @Override
  public void setMaxSize(int max) {
    A.ensure(max > 0, "max > 0");

    this.max = max;
  }
  /** {@inheritDoc} */
  @Override
  public GridFuture<Long> getAndAddAsync(long l) throws GridException {
    A.ensure(l > 0, " Parameter mustn't be less then 1: " + l);

    return internalUpdateAsync(l, null, false);
  }
  /**
   * Constructs random eviction policy with maximum size.
   *
   * @param max Maximum allowed size of cache before entry will start getting evicted.
   */
  public RandomEvictionPolicy(int max) {
    A.ensure(max > 0, "max > 0");

    this.max = max;
  }
  /**
   * Constructs FIFO eviction policy with maximum size. Empty entries are allowed.
   *
   * @param max Maximum allowed size of cache before entry will start getting evicted.
   */
  public GridCacheFifoEvictionPolicy(int max) {
    A.ensure(max > 0, "max > 0");

    this.max = max;
  }
  /** {@inheritDoc} */
  @Override
  public void perNodeBufferSize(int bufSize) {
    A.ensure(bufSize > 0, "bufSize > 0");

    this.bufSize = bufSize;
  }
  /** {@inheritDoc} */
  @Override
  public int countDown(int val) throws GridException {
    A.ensure(val > 0, "val should be positive");

    return CU.outTx(new CountDownCallable(val), ctx);
  }
  /**
   * Initializes tuple with given object count.
   *
   * @param cnt Count of objects to be stored in the tuple.
   */
  public GridTupleV(int cnt) {
    A.ensure(cnt > 0, "cnt > 0");

    vals = new Object[cnt];
  }
  /**
   * Sets given values starting at provided position in the tuple.
   *
   * @param pos Position to start from.
   * @param v Values to set.
   */
  public void set(int pos, Object... v) {
    A.ensure(pos > 0, "pos > 0");
    A.ensure(v.length + pos <= vals.length, "v.length + pos <= vals.length");

    if (v.length > 0) System.arraycopy(v, 0, vals, pos, v.length);
  }
  /**
   * Retrieves value at given index.
   *
   * @param i Index of the value to get.
   * @param <V> Value type.
   * @return Value at given index.
   */
  @SuppressWarnings({"unchecked"})
  public <V> V get(int i) {
    A.ensure(i < vals.length, "i < vals.length");

    return (V) vals[i];
  }
  /**
   * Constructs a new, empty map that orders its elements according to their {@linkplain Comparable
   * natural ordering}.
   *
   * @param max Upper bound of this map.
   */
  public GridBoundedConcurrentOrderedMap(int max) {
    A.ensure(max > 0, "max > 0");

    this.max = max;
  }
  /**
   * Sets value at given index.
   *
   * @param i Index to set.
   * @param v Value to set.
   * @param <V> Value type.
   */
  public <V> void set(int i, V v) {
    A.ensure(i < vals.length, "i < vals.length");

    vals[i] = v;
  }
  /**
   * Sets given values starting at {@code 0} position.
   *
   * @param v Values to set.
   */
  public void set(Object... v) {
    A.ensure(v.length <= vals.length, "v.length <= vals.length");

    if (v.length > 0) System.arraycopy(v, 0, vals, 0, v.length);
  }
  /** {@inheritDoc} */
  @Override
  public long addAndGet(long l) throws GridException {
    A.ensure(l > 0, " Parameter mustn't be less then 1: " + l);

    return internalUpdate(l, null, true);
  }
  /**
   * Asynchronous sequence update operation. Will add given amount to the sequence value.
   *
   * @param l Increment amount.
   * @param updateCall Cache call that will update sequence reservation count in accordance with l.
   * @param updated If {@code true}, will return sequence value after update, otherwise will return
   *     sequence value prior to update.
   * @return Future indicating sequence value.
   * @throws GridException If update failed.
   */
  private GridFuture<Long> internalUpdateAsync(
      long l, @Nullable Callable<Long> updateCall, boolean updated) throws GridException {
    checkRemoved();

    A.ensure(l > 0, " Parameter mustn't be less then 1: " + l);

    lock.lock();

    try {
      // If reserved range isn't exhausted.
      if (locVal + l <= upBound) {
        long curVal = locVal;

        locVal += l;

        return new GridFinishedFuture<Long>(ctx.kernalContext(), updated ? locVal : curVal);
      }
    } finally {
      lock.unlock();
    }

    if (updateCall == null) updateCall = internalUpdate(l, updated);

    while (true) {
      if (updateGuard.compareAndSet(false, true)) {
        try {
          // This call must be outside lock.
          return ctx.closures().callLocalSafe(updateCall, true);
        } finally {
          lock.lock();

          try {
            updateGuard.set(false);

            cond.signalAll();
          } finally {
            lock.unlock();
          }
        }
      } else {
        lock.lock();

        try {
          while (locVal >= upBound && updateGuard.get()) {
            try {
              cond.await(500, MILLISECONDS);
            } catch (InterruptedException e) {
              throw new GridInterruptedException(e);
            }
          }

          checkRemoved();

          // If reserved range isn't exhausted.
          if (locVal + l <= upBound) {
            long curVal = locVal;

            locVal += l;

            return new GridFinishedFuture<Long>(ctx.kernalContext(), updated ? locVal : curVal);
          }
        } finally {
          lock.unlock();
        }
      }
    }
  }
  /**
   * Gets value at given index within internal list. Note that this method will iterate through the
   * list to get a value at the specified index.
   *
   * @param idx Index to get value at (must be non-negative and less than {@link #size()}).
   * @return Value at give index.
   */
  public V get(int idx) {
    A.ensure(idx >= 0 && idx < size(), "idx >= 0 && idx < size()");

    return vals.get(idx);
  }