001/*
002 * JPPF.
003 * Copyright (C) 2005-2016 JPPF Team.
004 * http://www.jppf.org
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.jppf.utils.pooling;
020
021import java.util.concurrent.atomic.AtomicInteger;
022
023/**
024 * An extension of {@link AbstractObjectPoolQueue} which specifies a maximum size for the pool.
025 * <p>In this implementation, objects are still created dynamically if the pool is empty, however
026 * the <code>put(T)</code> method does not return an element to the backing queue if the pool size >= max size.
027 * <p> the {@link #size()} method is also overriden to provide results in constant time insteat of O(n) in
028 * the super class, since it is used frequently when comparing current pool size with the max size.
029 * @param <T> the type of the elements in the pool.
030 * @author Laurent Cohen
031 */
032public abstract class AbstractBoundedObjectPoolQueue<T> extends AbstractObjectPoolQueue<T> {
033  /**
034   * The current size of the pool.
035   */
036  protected AtomicInteger size = new AtomicInteger(0);
037  /**
038   * The pool max size.
039   */
040  protected final int maxSize;
041
042  /**
043   * Initialize this pool with the specified maximum size.
044   * @param maxSize the pool max size.
045   */
046  public AbstractBoundedObjectPoolQueue(final int maxSize) {
047    this.maxSize = maxSize;
048  }
049
050  @Override
051  public T get() {
052    T t = queue.poll();
053    if (t != null) size.decrementAndGet();
054    else t = create();
055    return t;
056  }
057
058  @Override
059  public void put(final T t) {
060    if (size.get() < maxSize) {
061      size.incrementAndGet();
062      queue.offer(t);
063    }
064  }
065
066  @Override
067  public int size() {
068    return size.get();
069  }
070}