001/*
002 * JPPF.
003 * Copyright (C) 2005-2018 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.client;
020
021import java.util.*;
022import java.util.concurrent.atomic.AtomicBoolean;
023
024import org.jppf.utils.*;
025import org.slf4j.*;
026
027/**
028 * An abstract implementation of the {@link ConnectionPool} interface.
029 * @param <E> the type of the connections in the pool.
030 * @author Laurent Cohen
031 * @since 4.2
032 */
033public abstract class AbstractConnectionPool<E extends AutoCloseable> implements ConnectionPool<E> {
034  /**
035   * Logger for this class.
036   */
037  private static Logger log = LoggerFactory.getLogger(AbstractConnectionPool.class);
038  /**
039   * Determines whether debug-level logging is enabled.
040   */
041  private static boolean debugEnabled = LoggingUtils.isDebugEnabled(log);
042  /**
043   * The max size of this pool.
044   */
045  int size;
046  /**
047   * Index of the last used connection in this pool.
048   */
049  private int lastUsedIndex = 0;
050  /**
051   * List of connection objects handled by this poool.
052   */
053  final List<E> connections = new ArrayList<>();
054  /**
055   * Whether this pool is closed.
056   */
057  final AtomicBoolean closed = new AtomicBoolean(false);
058
059  /**
060   * Initialize this pool with the specfiied core size.
061   * @param size the minimum number of connections in this pool.
062   */
063  protected AbstractConnectionPool(final int size) {
064    if (size < 1) throw new IllegalArgumentException("the pool size should be >= 1, but it is " + size);
065    this.size = size;
066  }
067
068  /**
069   * {@inheritDoc}
070   * @exclude
071   */
072  @Override
073  public synchronized boolean add(final E connection) {
074    if (debugEnabled) log.debug("adding {} to {}", connection, this);
075    return connections.add(connection);
076  }
077
078  /**
079   * {@inheritDoc}
080   * @exclude
081   */
082  @Override
083  public synchronized boolean remove(final E connection) {
084    if (debugEnabled) log.debug("removing {} from {}", connection, this);
085    if (connections.remove(connection)) {
086      if (lastUsedIndex >= connections.size() && lastUsedIndex > 0) lastUsedIndex--;
087      return true;
088    }
089    return false;
090  }
091
092  /**
093   * {@inheritDoc}
094   * @exclude
095   */
096  @Override
097  public synchronized E nextConnection() {
098    if (connections.isEmpty()) return null;
099    lastUsedIndex = ++lastUsedIndex % connections.size();
100    return connections.get(lastUsedIndex);
101  }
102
103  @Override
104  public synchronized boolean isEmpty() {
105    return connections.isEmpty();
106  }
107
108  @Override
109  public synchronized int connectionCount() {
110    return connections.size();
111  }
112
113  @Override
114  public synchronized List<E> getConnections() {
115    return new ArrayList<>(connections);
116  }
117
118  @Override
119  public synchronized Iterator<E> iterator() {
120    return connections.iterator();
121  }
122
123  /**
124   * Get the connection at the specified index.
125   * @param i the index to look at.
126   * @return a connection object.
127   * @since 5.1
128   */
129  synchronized E getConnection(final int i) {
130    return connections.get(i);
131  }
132
133  @Override
134  public synchronized int getSize() {
135    return size;
136  }
137
138  @Override
139  public void close() {
140    if (closed.compareAndSet(false, true)) {
141      final List<E> connections = getConnections();
142      for (final E connection: connections) {
143        try {
144          connection.close();
145        } catch(final Exception e) {
146          final String format = "error while closing connection {} : {}";
147          if (debugEnabled) log.debug(format, connection, ExceptionUtils.getMessage(e));
148          else log.warn(format, connection, ExceptionUtils.getStackTrace(e));
149        }
150      }
151      synchronized(this) {
152        this.connections.clear();
153      }
154    }
155  }
156
157  @Override
158  public String toString() {
159    final StringBuilder sb = new StringBuilder(getClass().getSimpleName()).append('[');
160    sb.append(", size=").append(size);
161    sb.append(", connectionCount=").append(connectionCount());
162    sb.append(']');
163    return sb.toString();
164  }
165}