1   /**
2    *  Copyright 2003-2007 Greg Luck
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  
17  package net.sf.ehcache.constructs.concurrent;
18  
19  import junit.framework.TestCase;
20  import net.sf.ehcache.CacheException;
21  import org.apache.commons.logging.Log;
22  import org.apache.commons.logging.LogFactory;
23  
24  /**
25   * Isolation tests for ConcurrencyUtil
26   *
27   * @author Greg Luck
28   * @version $Id: ConcurrencyUtilTest.java 512 2007-07-10 09:18:45Z gregluck $
29   */
30  public class ConcurrencyUtilTest extends TestCase {
31  
32      private static final Log LOG = LogFactory.getLog(ConcurrencyUtilTest.class.getName());
33  
34  
35      /**
36       * Tests that stripes are evently distributed
37       */
38      public void testStripingDistribution() {
39  
40          int[] lockIndexes = new int[2048];
41          for (int i = 0; i < 20480 * 3; i++) {
42              String key = "" + i * 3 / 2 + i;
43              key += key.hashCode();
44              int lock = ConcurrencyUtil.selectLock(key, 2048);
45              lockIndexes[lock]++;
46          }
47  
48          int outliers = 0;
49          for (int i = 0; i < 2048; i++) {
50              if (20 <= lockIndexes[i] && lockIndexes[i] <= 40) {
51                  continue;
52              }
53              LOG.info(i + ": " + lockIndexes[i]);
54              outliers++;
55          }
56          assertTrue(outliers <= 128);
57      }
58  
59      /**
60       * Tests edge conditions for striping mechanism.
61       */
62      public void testNullKey() {
63          ConcurrencyUtil.selectLock(null, 2048);
64          ConcurrencyUtil.selectLock("", 2048);
65      }
66  
67  
68      /**
69       * Tests edge conditions for striping mechanism.
70       */
71      public void testEvenLockNumber() {
72          try {
73              ConcurrencyUtil.selectLock("anything", 100);
74          } catch (CacheException e) {
75              //expected
76          }
77      }
78  
79  
80  }