001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * https://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.bcel.classfile; 020 021import java.io.DataInput; 022import java.io.DataOutputStream; 023import java.io.IOException; 024import java.util.HashMap; 025import java.util.LinkedHashMap; 026import java.util.Map; 027import java.util.Objects; 028 029import org.apache.bcel.Const; 030 031/** 032 * Extends the abstract {@link Constant} to represent a reference to a UTF-8 encoded string. 033 * <p> 034 * The following system properties govern caching this class performs. 035 * </p> 036 * <ul> 037 * <li>{@link #SYS_PROP_CACHE_MAX_ENTRIES} (since 6.4): The size of the cache, by default 0, meaning caching is 038 * disabled.</li> 039 * <li>{@link #SYS_PROP_CACHE_MAX_ENTRY_SIZE} (since 6.0): The maximum size of the values to cache, by default 200, 0 040 * disables caching. Values larger than this are <em>not</em> cached.</li> 041 * <li>{@link #SYS_PROP_STATISTICS} (since 6.0): Prints statistics on the console when the JVM exits.</li> 042 * </ul> 043 * <p> 044 * Here is a sample Maven invocation with caching disabled: 045 * </p> 046 * 047 * <pre> 048 * mvn test -Dbcel.statistics=true -Dbcel.maxcached.size=0 -Dbcel.maxcached=0 049 * </pre> 050 * <p> 051 * Here is a sample Maven invocation with caching enabled: 052 * </p> 053 * 054 * <pre> 055 * mvn test -Dbcel.statistics=true -Dbcel.maxcached.size=100000 -Dbcel.maxcached=5000000 056 * </pre> 057 * 058 * @see Constant 059 */ 060public final class ConstantUtf8 extends Constant { 061 062 private static final class Cache { 063 064 private static final boolean BCEL_STATISTICS = Boolean.getBoolean(SYS_PROP_STATISTICS); 065 private static final int MAX_ENTRIES = Integer.getInteger(SYS_PROP_CACHE_MAX_ENTRIES, 0).intValue(); 066 private static final int INITIAL_CAPACITY = (int) (MAX_ENTRIES / 0.75); 067 068 private static final HashMap<String, ConstantUtf8> CACHE = new LinkedHashMap<String, ConstantUtf8>(INITIAL_CAPACITY, 0.75f, true) { 069 070 private static final long serialVersionUID = -8506975356158971766L; 071 072 @Override 073 protected boolean removeEldestEntry(final Map.Entry<String, ConstantUtf8> eldest) { 074 return size() > MAX_ENTRIES; 075 } 076 }; 077 078 // Set the size to 0 or below to skip caching entirely 079 private static final int MAX_ENTRY_SIZE = Integer.getInteger(SYS_PROP_CACHE_MAX_ENTRY_SIZE, 200).intValue(); 080 081 static boolean isEnabled() { 082 return MAX_ENTRIES > 0 && MAX_ENTRY_SIZE > 0; 083 } 084 085 } 086 087 private static final Object LOCK = new Object(); 088 // TODO these should perhaps be AtomicInt? 089 private static volatile int considered; 090 private static volatile int created; 091 private static volatile int hits; 092 private static volatile int skipped; 093 094 private static final String SYS_PROP_CACHE_MAX_ENTRIES = "bcel.maxcached"; 095 private static final String SYS_PROP_CACHE_MAX_ENTRY_SIZE = "bcel.maxcached.size"; 096 private static final String SYS_PROP_STATISTICS = "bcel.statistics"; 097 098 static { 099 if (Cache.BCEL_STATISTICS) { 100 Runtime.getRuntime().addShutdownHook(new Thread(ConstantUtf8::printStats)); 101 } 102 } 103 104 /** 105 * Clears the cache. 106 * 107 * @since 6.4.0 108 */ 109 public static void clearCache() { 110 synchronized (LOCK) { 111 Cache.CACHE.clear(); 112 } 113 } 114 115 // for access by test code 116 static synchronized void clearStats() { 117 hits = considered = skipped = created = 0; 118 } 119 120 // Avoid Spotbugs complaint about Write to static field 121 private static synchronized void countCreated() { 122 created++; 123 } 124 125 /** 126 * Gets a new or cached instance of the given value. 127 * <p> 128 * See {@link ConstantUtf8} class Javadoc for details. 129 * </p> 130 * 131 * @param value The value. 132 * @return A new or cached instance of the given value. 133 * @since 6.0 134 */ 135 public static ConstantUtf8 getCachedInstance(final String value) { 136 synchronized (LOCK) { 137 if (value.length() > Cache.MAX_ENTRY_SIZE) { 138 skipped++; 139 return new ConstantUtf8(value); 140 } 141 considered++; 142 synchronized (ConstantUtf8.class) { // might be better with a specific lock object 143 ConstantUtf8 result = Cache.CACHE.get(value); 144 if (result != null) { 145 hits++; 146 return result; 147 } 148 result = new ConstantUtf8(value); 149 Cache.CACHE.put(value, result); 150 return result; 151 } 152 } 153 } 154 155 /** 156 * Gets a new or cached instance of the given value. 157 * <p> 158 * See {@link ConstantUtf8} class Javadoc for details. 159 * </p> 160 * 161 * @param dataInput The value. 162 * @return A new or cached instance of the given value. 163 * @throws IOException Thrown if an I/O error occurs. 164 * @since 6.0 165 */ 166 public static ConstantUtf8 getInstance(final DataInput dataInput) throws IOException { 167 return getInstance(dataInput.readUTF()); 168 } 169 170 /** 171 * Gets a new or cached instance of the given value. 172 * <p> 173 * See {@link ConstantUtf8} class Javadoc for details. 174 * </p> 175 * 176 * @param value The value. 177 * @return A new or cached instance of the given value. 178 * @since 6.0 179 */ 180 public static ConstantUtf8 getInstance(final String value) { 181 return Cache.isEnabled() ? getCachedInstance(value) : new ConstantUtf8(value); 182 } 183 184 // for access by test code 185 static void printStats() { 186 final String prefix = "[Apache Commons BCEL]"; 187 System.err.printf("%s Cache hit %,d/%,d, %d skipped.%n", prefix, hits, considered, skipped); 188 System.err.printf("%s Total of %,d ConstantUtf8 objects created.%n", prefix, created); 189 System.err.printf("%s Configuration: %s=%,d, %s=%,d.%n", prefix, SYS_PROP_CACHE_MAX_ENTRIES, Cache.MAX_ENTRIES, SYS_PROP_CACHE_MAX_ENTRY_SIZE, 190 Cache.MAX_ENTRY_SIZE); 191 } 192 193 private final String value; 194 195 /** 196 * Initializes from another object. 197 * 198 * @param constantUtf8 The value. 199 */ 200 public ConstantUtf8(final ConstantUtf8 constantUtf8) { 201 this(constantUtf8.getBytes()); 202 } 203 204 /** 205 * Initializes instance from file data. 206 * 207 * @param dataInput Input stream. 208 * @throws IOException Thrown if an I/O error occurs. 209 */ 210 ConstantUtf8(final DataInput dataInput) throws IOException { 211 super(Const.CONSTANT_Utf8); 212 value = dataInput.readUTF(); 213 countCreated(); 214 } 215 216 /** 217 * Constructs a ConstantUtf8. 218 * 219 * @param value Data. 220 */ 221 public ConstantUtf8(final String value) { 222 super(Const.CONSTANT_Utf8); 223 this.value = Objects.requireNonNull(value, "value"); 224 countCreated(); 225 } 226 227 /** 228 * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class. 229 * I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects. 230 * 231 * @param v Visitor object. 232 */ 233 @Override 234 public void accept(final Visitor v) { 235 v.visitConstantUtf8(this); 236 } 237 238 /** 239 * Dumps String in Utf8 format to file stream. 240 * 241 * @param file Output file stream. 242 * @throws IOException Thrown if an I/O error occurs. 243 */ 244 @Override 245 public void dump(final DataOutputStream file) throws IOException { 246 file.writeByte(super.getTag()); 247 file.writeUTF(value); 248 } 249 250 /** 251 * Gets the data converted to string. 252 * 253 * @return Data converted to string. 254 */ 255 public String getBytes() { 256 return value; 257 } 258 259 /** 260 * @param bytes The raw bytes of this UTF-8. 261 * @deprecated (since 6.0) 262 */ 263 @java.lang.Deprecated 264 public void setBytes(final String bytes) { 265 throw new UnsupportedOperationException(); 266 } 267 268 /** 269 * @return String representation. 270 */ 271 @Override 272 public String toString() { 273 return super.toString() + "(\"" + Utility.replace(value, "\n", "\\n") + "\")"; 274 } 275}