001 /*
002 * $Id: RuntimeTester.java,v 1.3 2011/07/09 21:43:22 oboehm Exp $
003 *
004 * Copyright (c) 2011 by Oliver Boehm
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 orimplied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 *
018 * (c)reated 09.05.2011 by oliver (ob@oasd.de)
019 */
020
021 package patterntesting.runtime.junit;
022
023 import org.apache.commons.lang.SystemUtils;
024 import org.slf4j.*;
025
026 /**
027 * This is a tester to do some runtime checking like memory checks and other
028 * stuff.
029 *
030 * @author oliver
031 * @since 1.1.1 (09.05.2011)
032 */
033 public final class RuntimeTester {
034
035 private static final Logger log = LoggerFactory.getLogger(RuntimeTester.class);
036
037 /** Utility class - no need to instantiate it. */
038 private RuntimeTester() {}
039
040 /**
041 * If you have some tests which needs a certain amount of memory this test
042 * is for you. This tests guarantees you that the VM is started with enough
043 * memory (usually option "-Xmx").
044 *
045 * @param required the max memory in MB
046 */
047 public static void assertMaxMemory(final int required) {
048 long mem = (Runtime.getRuntime().maxMemory() + 0x7FFFF) / 0x100000;
049 log.debug("VM was started with " + mem + " MB max memory.");
050 if (required > mem) {
051 String hint = (" (use 'java -Xmx" + required + "m ...')");
052 if (SystemUtils.JAVA_VENDOR.toUpperCase().startsWith("IBM")) {
053 hint = "";
054 }
055 throw new AssertionError(required + " MB max memory required but only " + mem
056 + " MB available" + hint);
057 }
058 }
059
060 /**
061 * If you need a certain amount of free memory you can assert it with this
062 * method here.
063 *
064 * @param required the required free memory in MB
065 */
066 public static void assertFreeMemory(final int required) {
067 long free = Runtime.getRuntime().freeMemory() / 0x100000;
068 if (required > free) {
069 System.gc();
070 }
071 free = (Runtime.getRuntime().freeMemory() + 0x7FFFF) / 0x100000;
072 log.debug(free + " MB memory is free.");
073 if (required > free) {
074 long maxMem = Runtime.getRuntime().maxMemory() / 0x100000 + required + 4 - free;
075 String hint = " (use 'try -Xmx" + maxMem + "m ...')";
076 throw new AssertionError(required + " MB free memory required but only " + free
077 + " MB are free" + hint);
078 }
079 }
080
081 }
082