1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.monitoring.jta;
18
19 import org.apache.commons.monitoring.gauges.Gauge;
20 import org.apache.commons.monitoring.repositories.Repository;
21 import org.junit.AfterClass;
22 import org.junit.BeforeClass;
23 import org.junit.Test;
24
25 import javax.ejb.EJB;
26 import javax.ejb.Lock;
27 import javax.ejb.LockType;
28 import javax.ejb.Singleton;
29 import javax.ejb.embeddable.EJBContainer;
30 import java.util.Collection;
31 import java.util.concurrent.CountDownLatch;
32 import java.util.concurrent.ExecutorService;
33 import java.util.concurrent.Executors;
34
35 import static org.junit.Assert.assertEquals;
36
37 public class GaugesTest {
38 private static final int ITERATIONS = 500;
39
40 private static Gauge.LoaderHelper gaugeLoader;
41
42 @BeforeClass
43 public static void init() {
44 Repository.INSTANCE.clear();
45 gaugeLoader = new Gauge.LoaderHelper(false);
46 }
47
48 @AfterClass
49 public static void reset() {
50 Repository.INSTANCE.clear();
51 gaugeLoader.destroy();
52 }
53
54 @EJB
55 private EjbWithJTASupport jtaSupport;
56
57 @Test
58 public void test() throws Exception {
59 final EJBContainer container = EJBContainer.createEJBContainer();
60 container.getContext().bind("inject", this);
61
62 final long start = System.currentTimeMillis();
63
64 final CountDownLatch latch = new CountDownLatch(ITERATIONS);
65 try {
66 final ExecutorService es = Executors.newFixedThreadPool(50);
67 for (int i = 0; i < ITERATIONS; i++) {
68 es.submit(new Runnable() {
69 @Override
70 public void run() {
71 jtaSupport.commit();
72 try {
73 jtaSupport.rollback();
74 } finally {
75 latch.countDown();
76 }
77 }
78 });
79 }
80 es.shutdown();
81 latch.await();
82
83 Thread.sleep(500);
84
85 final long end = System.currentTimeMillis();
86
87 assertEquals(ITERATIONS, sum(Repository.INSTANCE.getGaugeValues(start, end, JTAGauges.JTA_COMMITED).values()), 0);
88 assertEquals(ITERATIONS, sum(Repository.INSTANCE.getGaugeValues(start, end, JTAGauges.JTA_ROLLBACKED).values()), 0);
89
90
91 assertEquals(ITERATIONS / 2, sum(Repository.INSTANCE.getGaugeValues(start, end, JTAGauges.JTA_ACTIVE).values()), ITERATIONS * .1);
92 } finally {
93 container.close();
94 }
95 }
96
97 private double sum(final Collection<Double> values) {
98 double sum = 0;
99 for (final Double d : values) {
100 sum += d;
101 }
102 return sum;
103 }
104
105 @Singleton
106 @Lock(LockType.READ)
107 @JTAMonitored
108 public static class EjbWithJTASupport {
109 public void commit() {
110 try {
111 Thread.sleep(50);
112 } catch (final InterruptedException e) {
113
114 }
115 }
116
117 public void rollback() {
118 throw new NullPointerException();
119 }
120 }
121 }