1
2
3
4
5
6
7
8
9
10
11
12
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
23
24
25
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 }