Home | History | Annotate | Download | only in share
      1 /*
      2  * Licensed to the Apache Software Foundation (ASF) under one or more
      3  * contributor license agreements.  See the NOTICE file distributed with
      4  * this work for additional information regarding copyright ownership.
      5  * The ASF licenses this file to You under the Apache License, Version 2.0
      6  * (the "License"); you may not use this file except in compliance with
      7  * the License.  You may obtain a copy of the License at
      8  *
      9  *     http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  *  Unless required by applicable law or agreed to in writing, software
     12  *  distributed under the License is distributed on an "AS IS" BASIS,
     13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  *
     15  *  See the License for the specific language governing permissions and
     16  *  limitations under the License.
     17  */
     18 
     19 package org.apache.harmony.jpda.tests.share;
     20 
     21 import java.lang.ref.PhantomReference;
     22 import java.lang.ref.ReferenceQueue;
     23 import java.util.ArrayList;
     24 
     25 /**
     26  * A class that allows one to observe GCs and finalization.
     27  */
     28 public class GcMarker {
     29 
     30   private final ReferenceQueue mQueue;
     31   private final ArrayList<PhantomReference> mList;
     32 
     33   public GcMarker() {
     34     mQueue = new ReferenceQueue();
     35     mList = new ArrayList<PhantomReference>(3);
     36   }
     37 
     38   public void add(Object referent) {
     39     mList.add(new PhantomReference(referent, mQueue));
     40   }
     41 
     42   public void waitForGc(int numberOfExpectedFinalizations) {
     43     if (numberOfExpectedFinalizations > mList.size()) {
     44       throw new IllegalArgumentException("wait condition will never be met");
     45     }
     46 
     47     // Request finalization of objects, and subsequent reference enqueueing.
     48     // Repeat until reference queue reaches expected size.
     49     do {
     50         System.runFinalization();
     51         Runtime.getRuntime().gc();
     52         try { Thread.sleep(10); } catch (Exception e) {}
     53     } while (isLive(numberOfExpectedFinalizations));
     54   }
     55 
     56   private boolean isLive(int numberOfExpectedFinalizations) {
     57     int numberFinalized = 0;
     58     for (int i = 0, n = mList.size(); i < n; i++) {
     59       if (mList.get(i).isEnqueued()) {
     60         numberFinalized++;
     61       }
     62     }
     63     return numberFinalized < numberOfExpectedFinalizations;
     64   }
     65 }
     66