001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 * 017 */ 018package org.apache.bcel.util; 019 020import java.lang.ref.SoftReference; 021import java.util.HashMap; 022import java.util.Map; 023 024import org.apache.bcel.classfile.JavaClass; 025 026/** 027 * This repository is used in situations where a Class is created outside the realm of a ClassLoader. Classes are loaded 028 * from the file systems using the paths specified in the given class path. By default, this is the value returned by 029 * ClassPath.getClassPath(). This repository holds onto classes with SoftReferences, and will reload as needed, in cases 030 * where memory sizes are important. 031 * 032 * @see org.apache.bcel.Repository 033 */ 034public class MemorySensitiveClassPathRepository extends AbstractClassPathRepository { 035 036 private final Map<String, SoftReference<JavaClass>> loadedClasses = new HashMap<>(); // CLASSNAME X JAVACLASS 037 038 public MemorySensitiveClassPathRepository(final ClassPath path) { 039 super(path); 040 } 041 042 /** 043 * Clear all entries from cache. 044 */ 045 @Override 046 public void clear() { 047 loadedClasses.clear(); 048 } 049 050 /** 051 * Find an already defined (cached) JavaClass object by name. 052 */ 053 @Override 054 public JavaClass findClass(final String className) { 055 final SoftReference<JavaClass> ref = loadedClasses.get(className); 056 if (ref == null) { 057 return null; 058 } 059 return ref.get(); 060 } 061 062 /** 063 * Remove class from repository 064 */ 065 @Override 066 public void removeClass(final JavaClass clazz) { 067 loadedClasses.remove(clazz.getClassName()); 068 } 069 070 /** 071 * Store a new JavaClass instance into this Repository. 072 */ 073 @Override 074 public void storeClass(final JavaClass clazz) { 075 // Not calling super.storeClass because this subclass maintains the mapping. 076 loadedClasses.put(clazz.getClassName(), new SoftReference<>(clazz)); 077 clazz.setRepository(this); 078 } 079}