1 /*
   2  * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 package gc.g1.plab.lib;
  24 
  25 /**
  26  * The Storage is used for storing reachable objects.
  27  * Class will store not more than capacity, which can be set during creation.
  28  * If we exceed capacity, object will be stored at existing entries.
  29  * So, if capacity=1, all previously added objects will be unreachable.
  30  */
  31 public class Storage {
  32 
  33     private int capacity;
  34 
  35     private Object[] array;
  36     private int index;
  37 
  38     /**
  39      * Create Storage object with defined capacity
  40      *
  41      * @param capacity
  42      */
  43     public Storage(int capacity) {
  44         if (capacity <= 0) {
  45             throw new IllegalArgumentException("Items number should be greater than 0.");
  46         }
  47         this.capacity = capacity;
  48         index = 0;
  49         array = new Object[this.capacity];
  50     }
  51 
  52     /**
  53      * Store object into Storage.
  54      *
  55      * @param o - Object to store
  56      */
  57     public void store(Object o) {
  58         if (array == null) {
  59             throw new RuntimeException("Capacity should be set before storing");
  60         }
  61         array[index % capacity] = o;
  62         ++index;
  63     }
  64 
  65     /**
  66      * Clear all stored objects.
  67      */
  68     public void clear() {
  69         array = null;
  70     }
  71 }