1 /* 2 * Copyright (c) 2016, 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 MemoryConsumer is used for consuming different amount of memory. 27 * Class will store not more than 'capacity' number of objects with 'chunk' size. 28 * If we exceed capacity, object will be stored at existing entries, 29 * all previously added objects will be overwritten. 30 * If capacity=1, only last object will be saved. 31 */ 32 public class MemoryConsumer { 33 34 private int capacity; 35 private int chunk; 36 37 private Object[] array; 38 private int index; 39 40 /** 41 * Create MemoryConsumer object with defined capacity 42 * 43 * @param capacity 44 * @param chunk 45 */ 46 public MemoryConsumer(int capacity, int chunk) { 47 if (capacity <= 0) { 48 throw new IllegalArgumentException("Items number should be greater than 0."); 49 } 50 if (chunk <= 0) { 51 throw new IllegalArgumentException("Chunk size should be greater than 0."); 52 } 53 this.capacity = capacity; 54 this.chunk = chunk; 55 index = 0; 56 array = new Object[this.capacity]; 57 } 58 59 /** 60 * Store object into Storage. 61 * 62 * @param o - Object to store 63 */ 64 private void store(Object o) { 65 if (array == null) { 66 throw new RuntimeException("Capacity should be set before storing"); 67 } 68 array[index % capacity] = o; 69 ++index; 70 } 71 72 public void consume(long memoryToFill) { 73 long allocated = 0; 74 while (allocated < memoryToFill) { 75 store(new byte[chunk]); 76 allocated += chunk; 77 } 78 } 79 80 /** 81 * Clear all stored objects. 82 */ 83 public void clear() { 84 array = null; 85 } 86 }