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 */
017package org.apache.bcel.util;
018
019import java.lang.ref.SoftReference;
020import java.util.HashMap;
021import java.util.Map;
022
023import org.apache.bcel.classfile.JavaClass;
024
025/**
026 * This repository is used in situations where a Class is created outside the realm of a ClassLoader. Classes are loaded
027 * from the file systems using the paths specified in the given class path. By default, this is the value returned by
028 * ClassPath.getClassPath(). This repository holds onto classes with SoftReferences, and will reload as needed, in cases
029 * where memory sizes are important.
030 *
031 * @see org.apache.bcel.Repository
032 */
033public class MemorySensitiveClassPathRepository extends AbstractClassPathRepository {
034
035    private final Map<String, SoftReference<JavaClass>> loadedClasses = new HashMap<>(); // CLASSNAME X JAVACLASS
036
037    public MemorySensitiveClassPathRepository(final ClassPath path) {
038        super(path);
039    }
040
041    /**
042     * Clear all entries from cache.
043     */
044    @Override
045    public void clear() {
046        loadedClasses.clear();
047    }
048
049    /**
050     * Find an already defined (cached) JavaClass object by name.
051     */
052    @Override
053    public JavaClass findClass(final String className) {
054        final SoftReference<JavaClass> ref = loadedClasses.get(className);
055        return ref == null ? null : ref.get();
056    }
057
058    /**
059     * Remove class from repository
060     */
061    @Override
062    public void removeClass(final JavaClass clazz) {
063        loadedClasses.remove(clazz.getClassName());
064    }
065
066    /**
067     * Store a new JavaClass instance into this Repository.
068     */
069    @Override
070    public void storeClass(final JavaClass clazz) {
071        // Not calling super.storeClass because this subclass maintains the mapping.
072        loadedClasses.put(clazz.getClassName(), new SoftReference<>(clazz));
073        clazz.setRepository(this);
074    }
075}