001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.kernel.test;
016    
017    import java.lang.ref.ReferenceQueue;
018    import java.lang.ref.SoftReference;
019    import java.lang.ref.WeakReference;
020    
021    import java.util.ArrayList;
022    import java.util.List;
023    
024    import org.junit.Assert;
025    
026    /**
027     * @author Shuyang Zhou
028     */
029    public class GCUtil {
030    
031            public static void fullGC() throws InterruptedException {
032                    ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>();
033    
034                    SoftReference<Object> softReference = new SoftReference<Object>(
035                            new Object(), referenceQueue);
036    
037                    List<byte[]> list = new ArrayList<byte[]>();
038    
039                    while (true) {
040                            try {
041                                    list.add(new byte[100 * 1024 * 1024]);
042                            }
043                            catch (OutOfMemoryError oome) {
044                                    list.clear();
045    
046                                    break;
047                            }
048                    }
049    
050                    Assert.assertNull(softReference.get());
051                    Assert.assertSame(softReference, referenceQueue.remove());
052            }
053    
054            public static void gc() throws InterruptedException {
055                    ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>();
056    
057                    WeakReference<Object> weakReference = new WeakReference<Object>(
058                            new Object(), referenceQueue);
059    
060                    while (weakReference.get() != null) {
061                            System.gc();
062    
063                            System.runFinalization();
064                    }
065    
066                    Assert.assertSame(weakReference, referenceQueue.remove());
067            }
068    
069    }