View Javadoc
1   /**
2    * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the
3    * COPYRIGHT.txt in the distribution for a full listing of individual contributors.
4    * 
5    * This is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser
6    * General Public License as published by the Free Software Foundation; either version 3.0 of the
7    * License, or (at your option) any later version.
8    * 
9    * This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
10   * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11   * GNU Lesser General Public License for more details.
12   * 
13   * You should have received a copy of the GNU Lesser General Public License along with this
14   * software; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
15   * Boston, MA 02110-1301 USA, or see the FSF site: http://www.fsf.org.
16   */
17  package org.waarp.gateway.ftp.config;
18  
19  import java.util.concurrent.atomic.AtomicInteger;
20  
21  /**
22   * Circular Value used by passive connections to find the next valid port to propose to the client.
23   * 
24   * @author Frederic Bregier
25   * 
26   */
27  class CircularIntValue {
28      /**
29       * Min value
30       */
31      private final int min;
32  
33      /**
34       * Max value
35       */
36      private final int max;
37  
38      /**
39       * Current Value
40       */
41      private AtomicInteger current;
42  
43      /**
44       * Create a circular range of values
45       * 
46       * @param min
47       * @param max
48       */
49      public CircularIntValue(int min, int max) {
50          this.min = min;
51          this.max = max;
52          current = new AtomicInteger(this.min - 1);
53      }
54  
55      /**
56       * Get the next value
57       * 
58       * @return the next value
59       */
60      public int getNext() {
61          synchronized (current) {
62              if (!current.compareAndSet(max, min)) {
63                  current.incrementAndGet();
64              }
65              return current.get();
66          }
67      }
68  }