2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 package org.apache.lucene.util;
19 import java.util.Random;
21 public class TestStringIntern extends LuceneTestCase {
23 String[] internedStrings;
25 private String randStr(int len) {
26 char[] arr = new char[len];
27 for (int i=0; i<len; i++) {
28 arr[i] = (char)('a' + random.nextInt(26));
30 return new String(arr);
33 private void makeStrings(int sz) {
34 testStrings = new String[sz];
35 internedStrings = new String[sz];
36 for (int i=0; i<sz; i++) {
37 testStrings[i] = randStr(random.nextInt(8)+3);
41 public void testStringIntern() throws InterruptedException {
42 makeStrings(1024*10); // something greater than the capacity of the default cache size
43 // makeStrings(100); // realistic for perf testing
45 // final int iter=100000;
46 final int iter = atLeast(100000);
49 // StringHelper.interner = new StringInterner();
51 Thread[] threads = new Thread[nThreads];
52 for (int i=0; i<nThreads; i++) {
54 threads[i] = new Thread() {
57 Random rand = new Random(seed);
58 String[] myInterned = new String[testStrings.length];
59 for (int j=0; j<iter; j++) {
60 int idx = rand.nextInt(testStrings.length);
61 String s = testStrings[idx];
62 if (rand.nextBoolean()) s = new String(s); // make a copy half of the time
63 String interned = StringHelper.intern(s);
64 String prevInterned = myInterned[idx];
65 String otherInterned = internedStrings[idx];
67 // test against other threads
68 if (otherInterned != null && otherInterned != interned) {
71 internedStrings[idx] = interned;
73 // test against local copy
74 if (prevInterned != null && prevInterned != interned) {
77 myInterned[idx] = interned;
85 for (int i=0; i<nThreads; i++) {