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.util.LinkedHashMap;
020import java.util.Map;
021
022import org.apache.bcel.classfile.JavaClass;
023
024/**
025 * Maintains a least-recently-used (LRU) cache of {@link JavaClass} with maximum size {@code cacheSize}.
026 *
027 * <p>
028 * This repository supports a class path consisting of too many JAR files to handle in {@link ClassPathRepository} or
029 * {@link MemorySensitiveClassPathRepository} without causing {@code OutOfMemoryError}.
030 * </p>
031 *
032 * @since 6.4.0
033 */
034public class LruCacheClassPathRepository extends AbstractClassPathRepository {
035
036    private final LinkedHashMap<String, JavaClass> loadedClasses;
037
038    public LruCacheClassPathRepository(final ClassPath path, final int cacheSize) {
039        super(path);
040
041        if (cacheSize < 1) {
042            throw new IllegalArgumentException("cacheSize must be a positive number.");
043        }
044        final int initialCapacity = (int) (0.75 * cacheSize);
045        final boolean accessOrder = true; // Evicts least-recently-accessed
046        loadedClasses = new LinkedHashMap<String, JavaClass>(initialCapacity, cacheSize, accessOrder) {
047
048            private static final long serialVersionUID = 1L;
049
050            @Override
051            protected boolean removeEldestEntry(final Map.Entry<String, JavaClass> eldest) {
052                return size() > cacheSize;
053            }
054        };
055    }
056
057    @Override
058    public void clear() {
059        loadedClasses.clear();
060    }
061
062    @Override
063    public JavaClass findClass(final String className) {
064        return loadedClasses.get(className);
065    }
066
067    @Override
068    public void removeClass(final JavaClass javaClass) {
069        loadedClasses.remove(javaClass.getClassName());
070    }
071
072    @Override
073    public void storeClass(final JavaClass javaClass) {
074        // Not storing parent's _loadedClass
075        loadedClasses.put(javaClass.getClassName(), javaClass);
076        javaClass.setRepository(this);
077    }
078}