01: /*
02: * Copyright (C) The MX4J Contributors.
03: * All rights reserved.
04: *
05: * This software is distributed under the terms of the MX4J License version 1.0.
06: * See the terms of the MX4J License in the documentation provided with this software.
07: */
08:
09: package mx4j.examples.mbeans.legacy;
10:
11: /**
12: * This service wakes up every once in a while, and does an intensive job
13: * spawning many threads to perform the given operation. <br>
14: * We would like to be informed of this activity, and would like to expose functionality of
15: * this service via JMX. To achieve these goals, we wrap it by means of a DynamicMBean,
16: * {@link DynamicLegacyService}.
17: *
18: * @version $Revision: 1.1 $
19: */
20: public class LegacyService {
21: private boolean running;
22: private ThreadGroup group = new ThreadGroup("Legacy Thread Group");
23:
24: /**
25: * This method is called 'execute', but we want to expose it in JMX with the name 'start'.
26: * The magic is done in the DynamicMBean that wraps this service to expose it via JMX.
27: */
28: public void execute() {
29: while (true) {
30: // Wait for a while
31: long wait = Math.round(Math.random() * 10000L) + 1;
32: try {
33: System.out.println("Waiting " + wait + " ms...");
34: Thread.sleep(wait);
35: } catch (InterruptedException ignored) {
36: }
37: // Ok, we've slept enough, time to do some job
38: synchronized (this ) {
39: running = true;
40: }
41:
42: Thread thread = new Thread(new Runnable() {
43: public void run() {
44: spawnThreads();
45: // We're done now, not running anymore
46: synchronized (this ) {
47: running = false;
48: }
49: }
50: });
51: thread.start();
52: try {
53: thread.join();
54: } catch (InterruptedException ignored) {
55: }
56: }
57: }
58:
59: /**
60: * This method is private in the legacy service. However, we want to expose it via JMX
61: * without modifying this service. The magic is done in the DynamicMBean that wraps this
62: * service to expose it via JMX.
63: */
64: private synchronized boolean isRunning() {
65: return running;
66: }
67:
68: private void spawnThreads() {
69: Thread[] threads = new Thread[20];
70: for (int i = 0; i < threads.length; ++i) {
71: threads[i] = new Thread(group, new Runnable() {
72: public void run() {
73: // Simulate a job: sleep for a while :D
74: long sleep = Math.round(Math.random() * 5000L) + 1;
75: try {
76: Thread.sleep(sleep);
77: } catch (InterruptedException ignored) {
78: }
79: }
80: });
81: threads[i].start();
82: }
83:
84: // Now wait for everyone to complete:
85: for (int i = 0; i < threads.length; ++i) {
86: try {
87: threads[i].join();
88: } catch (InterruptedException ignored) {
89: }
90: }
91: }
92: }
|