View Javadoc

1   /***
2    *  Copyright 2003-2010 Terracotta, Inc.
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.concurrent;
18  
19  
20  import net.sf.ehcache.CacheException;
21  
22  import static org.junit.Assert.assertTrue;
23  
24  import org.junit.Test;
25  
26  
27  import org.slf4j.Logger;
28  import org.slf4j.LoggerFactory;
29  
30  
31  /***
32   * Isolation tests for ConcurrencyUtil
33   *
34   * @author Greg Luck
35   * @version $Id: ConcurrencyUtilTest.html 13146 2011-08-01 17:12:39Z oletizi $
36   */
37  public class ConcurrencyUtilTest {
38  
39      private static final Logger LOG = LoggerFactory.getLogger(ConcurrencyUtilTest.class.getName());
40  
41  
42      /***
43       * Tests that stripes are evently distributed
44       */
45      @Test
46      public void testStripingDistribution() {
47  
48          int[] lockIndexes = new int[2048];
49          for (int i = 0; i < 20480 * 3; i++) {
50              String key = "" + i * 3 / 2 + i;
51              key += key.hashCode();
52              int lock = ConcurrencyUtil.selectLock(key, 2048);
53              lockIndexes[lock]++;
54          }
55  
56          int outliers = 0;
57          for (int i = 0; i < 2048; i++) {
58              if (20 <= lockIndexes[i] && lockIndexes[i] <= 40) {
59                  continue;
60              }
61              LOG.info(i + ": " + lockIndexes[i]);
62              outliers++;
63          }
64          assertTrue(outliers <= 128);
65      }
66  
67      /***
68       * Tests edge conditions for striping mechanism.
69       */
70      @Test
71      public void testNullKey() {
72          ConcurrencyUtil.selectLock(null, 2048);
73          ConcurrencyUtil.selectLock("", 2048);
74      }
75  
76  
77      /***
78       * Tests edge conditions for striping mechanism.
79       */
80      @Test
81      public void testEvenLockNumber() {
82          try {
83              ConcurrencyUtil.selectLock("anything", 100);
84          } catch (CacheException e) {
85              //expected
86          }
87      }
88  
89  
90  }