View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   https://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.bcel.classfile;
20  
21  import java.io.DataInput;
22  import java.io.DataOutputStream;
23  import java.io.IOException;
24  import java.util.HashMap;
25  import java.util.LinkedHashMap;
26  import java.util.Map;
27  import java.util.Objects;
28  
29  import org.apache.bcel.Const;
30  
31  /**
32   * Extends the abstract {@link Constant} to represent a reference to a UTF-8 encoded string.
33   * <p>
34   * The following system properties govern caching this class performs.
35   * </p>
36   * <ul>
37   * <li>{@link #SYS_PROP_CACHE_MAX_ENTRIES} (since 6.4): The size of the cache, by default 0, meaning caching is
38   * disabled.</li>
39   * <li>{@link #SYS_PROP_CACHE_MAX_ENTRY_SIZE} (since 6.0): The maximum size of the values to cache, by default 200, 0
40   * disables caching. Values larger than this are <em>not</em> cached.</li>
41   * <li>{@link #SYS_PROP_STATISTICS} (since 6.0): Prints statistics on the console when the JVM exits.</li>
42   * </ul>
43   * <p>
44   * Here is a sample Maven invocation with caching disabled:
45   * </p>
46   *
47   * <pre>
48   * mvn test -Dbcel.statistics=true -Dbcel.maxcached.size=0 -Dbcel.maxcached=0
49   * </pre>
50   * <p>
51   * Here is a sample Maven invocation with caching enabled:
52   * </p>
53   *
54   * <pre>
55   * mvn test -Dbcel.statistics=true -Dbcel.maxcached.size=100000 -Dbcel.maxcached=5000000
56   * </pre>
57   *
58   * @see Constant
59   */
60  public final class ConstantUtf8 extends Constant {
61  
62      private static final class Cache {
63  
64          private static final boolean BCEL_STATISTICS = Boolean.getBoolean(SYS_PROP_STATISTICS);
65          private static final int MAX_ENTRIES = Integer.getInteger(SYS_PROP_CACHE_MAX_ENTRIES, 0).intValue();
66          private static final int INITIAL_CAPACITY = (int) (MAX_ENTRIES / 0.75);
67  
68          private static final HashMap<String, ConstantUtf8> CACHE = new LinkedHashMap<String, ConstantUtf8>(INITIAL_CAPACITY, 0.75f, true) {
69  
70              private static final long serialVersionUID = -8506975356158971766L;
71  
72              @Override
73              protected boolean removeEldestEntry(final Map.Entry<String, ConstantUtf8> eldest) {
74                  return size() > MAX_ENTRIES;
75              }
76          };
77  
78          // Set the size to 0 or below to skip caching entirely
79          private static final int MAX_ENTRY_SIZE = Integer.getInteger(SYS_PROP_CACHE_MAX_ENTRY_SIZE, 200).intValue();
80  
81          static boolean isEnabled() {
82              return MAX_ENTRIES > 0 && MAX_ENTRY_SIZE > 0;
83          }
84  
85      }
86  
87      private static final Object LOCK = new Object();
88      // TODO these should perhaps be AtomicInt?
89      private static volatile int considered;
90      private static volatile int created;
91      private static volatile int hits;
92      private static volatile int skipped;
93  
94      private static final String SYS_PROP_CACHE_MAX_ENTRIES = "bcel.maxcached";
95      private static final String SYS_PROP_CACHE_MAX_ENTRY_SIZE = "bcel.maxcached.size";
96      private static final String SYS_PROP_STATISTICS = "bcel.statistics";
97  
98      static {
99          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 }