View Javadoc
1   /**
2    *  Copyright 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  package info.magnolia.cache.concurrent;
17  
18  import java.util.concurrent.ExecutorService;
19  import java.util.concurrent.TimeUnit;
20  
21  import net.spy.memcached.OperationTimeoutException;
22  
23  /**
24   * Various bits of black magic garnered from experts on the concurrency-interest@cs.oswego.edu mailing list.
25   *
26   * @author Greg Luck
27   * @version $Id: ConcurrencyUtil.java 7833 2013-07-25 01:00:20Z cschanck $
28   */
29  public final class ConcurrencyUtil {
30  
31      private static final int DOUG_LEA_BLACK_MAGIC_OPERAND_1 = 20;
32      private static final int DOUG_LEA_BLACK_MAGIC_OPERAND_2 = 12;
33      private static final int DOUG_LEA_BLACK_MAGIC_OPERAND_3 = 7;
34      private static final int DOUG_LEA_BLACK_MAGIC_OPERAND_4 = 4;
35  
36  
37      /**
38       * Utility class therefore precent construction.
39       */
40      private ConcurrencyUtil() {
41          //noop;
42      }
43  
44      /**
45       * Returns a hash code for non-null Object x.
46       * <p/>
47       * This function ensures that hashCodes that differ only by
48       * constant multiples at each bit position have a bounded
49       * number of collisions. (Doug Lea)
50       *
51       * @param object the object serving as a key
52       * @return the hash code
53       */
54      public static int hash(Object object) {
55          int h = object.hashCode();
56          h ^= (h >>> DOUG_LEA_BLACK_MAGIC_OPERAND_1) ^ (h >>> DOUG_LEA_BLACK_MAGIC_OPERAND_2);
57          return h ^ (h >>> DOUG_LEA_BLACK_MAGIC_OPERAND_3) ^ (h >>> DOUG_LEA_BLACK_MAGIC_OPERAND_4);
58      }
59  
60      /**
61       * Selects a lock for a key. The same lock is always used for a given key.
62       *
63       * @param key
64       * @return the selected lock index
65       */
66      public static int selectLock(final Object key, int numberOfLocks) {
67          int number = numberOfLocks & (numberOfLocks - 1);
68          if (number != 0) {
69              throw new IllegalStateException("Lock number must be a power of two: " + numberOfLocks);
70          }
71          if (key == null) {
72              return 0;
73          } else {
74              int hash = hash(key) & (numberOfLocks - 1);
75              return hash;
76          }
77  
78      }
79  
80  
81      /**
82       * Properly shutdown and await pool termination for an arbitrary
83       * amount of time.
84       *
85       * @param pool Pool to shutdown
86       * @param waitSeconds Seconds to wait before throwing exception
87       * @throws net.spy.memcached.OperationTimeoutException Thrown if the pool does not shutdown in the specified time
88       */
89      public static void shutdownAndWaitForTermination(ExecutorService pool, int waitSeconds) throws OperationTimeoutException {
90          // shut it down
91          pool.shutdown();
92          try {
93              // wait, wait, wait
94              if (!pool.awaitTermination(waitSeconds, TimeUnit.SECONDS)) {
95                  // things still running, nuke it
96                  pool.shutdownNow();
97                  // wait, wait, wai
98                  if (!pool.awaitTermination(waitSeconds, TimeUnit.SECONDS)) {
99                      // boo hiss, didn't shutdown
100                     throw new OperationTimeoutException("Pool did not terminate");
101                 }
102             }
103         } catch (InterruptedException ie) {
104             // try, try again
105             pool.shutdownNow();
106             Thread.currentThread().interrupt();
107         }
108     }
109 }