1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.monitoring;
19
20 import java.util.concurrent.ExecutorService;
21 import java.util.concurrent.Executors;
22 import java.util.concurrent.TimeUnit;
23
24 import junit.framework.TestCase;
25
26 import org.apache.commons.monitoring.impl.repositories.DefaultRepository;
27
28
29
30
31 public class MonitoringTest
32 extends TestCase
33 {
34 public final static Role<Counter> COUNTER = new Role<Counter>( "COUNTER", Unit.UNARY, Counter.class );
35
36 public final static Role<Gauge> GAUGE = new Role<Gauge>( "GAUGE", Unit.UNARY, Gauge.class );
37
38
39 public void testStopWatchConcurrencyMonitoring()
40 throws Exception
41 {
42 Monitoring.setRepository( new DefaultRepository() );
43
44 StopWatch stopWatch1 = Monitoring.start( "MonitoringTest.testMonitoring", "test", "utils" );
45 StopWatch stopWatch2 = Monitoring.start( "MonitoringTest.testMonitoring", "test", "utils" );
46 stopWatch2.stop();
47
48 Monitor monitor = Monitoring.getMonitor( "MonitoringTest.testMonitoring", "test", "utils" );
49 Gauge concurrency = monitor.getGauge( Monitor.CONCURRENCY );
50 assertEquals( 1, concurrency.get() );
51 assertEquals( 2, concurrency.getMax() );
52
53 stopWatch1.stop();
54 assertEquals( 0, concurrency.get() );
55 }
56
57 public void testThreadSafety()
58 throws Exception
59 {
60 int threads = 50;
61 final int loops = 10000;
62
63 Monitoring.setRepository( new DefaultRepository() );
64
65 StopWatch s = Monitoring.start( "testThreadSafety" );
66 ExecutorService pool = Executors.newFixedThreadPool( threads );
67 for ( int i = 0; i < threads; i++ )
68 {
69 pool.execute( new Runnable()
70 {
71 public void run()
72 {
73 for ( int j = 0; j < loops; j++ )
74 {
75 Monitor monitor = Monitoring.getMonitor( "MonitoringTest.testMultiThreading", "test", "utils" );
76 monitor.getCounter( COUNTER ).add( 1, Unit.UNARY );
77 monitor.getGauge( GAUGE ).increment(Unit.UNARY);
78 }
79 try
80 {
81 Thread.sleep( (long) ( Math.random() * 100 ) );
82 }
83 catch ( InterruptedException e )
84 {
85
86 }
87 }
88 } );
89 }
90 pool.shutdown();
91 pool.awaitTermination( 120, TimeUnit.SECONDS );
92
93 System.out.println( (threads * loops) + " executions took " + s.getElapsedTime() + "ns" );
94
95 Monitor monitor = Monitoring.getMonitor( "MonitoringTest.testMultiThreading", "test", "utils" );
96
97 Counter counter = monitor.getCounter( COUNTER );
98 assertEquals( counter.getClass() + " is not thread safe", threads * loops, counter.getHits() );
99 assertEquals( counter.getClass() + " is not thread safe", threads * loops, counter.get() );
100
101 Gauge gauge = monitor.getGauge( GAUGE );
102 assertEquals( gauge.getClass() + " is not thread safe", threads * loops, gauge.get() );
103 }
104
105 }