View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.issue;
15  
16  import java.util.concurrent.locks.Lock;
17  import java.util.concurrent.locks.ReentrantLock;
18  
19  import ch.qos.logback.core.contention.RunnableWithCounterAndDone;
20  
21  /**
22   * A runnable which behaves differently depending on the desired locking model.
23   * 
24   * @author Joern Huxhorn
25   * @author Ceki Gulcu
26   */
27  public class SelectiveLockRunnable extends RunnableWithCounterAndDone {
28  
29      enum LockingModel {
30          NOLOCK, SYNC, FAIR, UNFAIR;
31      }
32  
33      static Object LOCK = new Object();
34      static Lock FAIR_LOCK = new ReentrantLock(true);
35      static Lock UNFAIR_LOCK = new ReentrantLock(false);
36  
37      LockingModel model;
38  
39      SelectiveLockRunnable(LockingModel model) {
40          this.model = model;
41      }
42  
43      public void run() {
44          switch (model) {
45          case NOLOCK:
46              nolockRun();
47              break;
48          case SYNC:
49              synchronizedRun();
50              break;
51          case FAIR:
52              fairLockRun();
53              break;
54          case UNFAIR:
55              unfairLockRun();
56              break;
57          }
58      }
59  
60      void fairLockRun() {
61          for (;;) {
62              FAIR_LOCK.lock();
63              counter++;
64              FAIR_LOCK.unlock();
65              if (done) {
66                  return;
67              }
68          }
69      }
70  
71      void unfairLockRun() {
72          for (;;) {
73              UNFAIR_LOCK.lock();
74              counter++;
75              UNFAIR_LOCK.unlock();
76              if (done) {
77                  return;
78              }
79          }
80      }
81  
82      void nolockRun() {
83          for (;;) {
84              counter++;
85              if (done) {
86                  return;
87              }
88          }
89      }
90  
91      void synchronizedRun() {
92          for (;;) {
93              synchronized (LOCK) {
94                  counter++;
95              }
96              if (done) {
97                  return;
98              }
99          }
100     }
101 
102     @Override
103     public String toString() {
104         return "SelectiveLockRunnable " + model;
105     }
106 }