当前页面: 开发资料首页 → Netbeans 专题 → Adding Java Management Extensions (JMX) Instrumentation to a Java Application
Adding Java Management Extensions (JMX) Instrumentation to a Java Application
摘要: The NetBeans JMX Module integrates JMX technology right into your workflow in the NetBeans IDE. This module allows you to quickly develop management applications, add management to exisiting applications, develop manager applications, and monitor the state of the Virtual Machine. The module is available for NetBeans IDE version 4.0 and higher. You can install the module by choosing Tools > Update Center and downloading the module from the NetBeans Update Center.
Expected duration: 60 minutes
The NetBeans JMX Module integrates JMX technology right into your workflow
in the NetBeans IDE. This module allows you to quickly develop management applications,
add management to exisiting applications, develop manager applications, and
monitor the state of the Virtual Machine. The module is available for NetBeans
IDE version 4.0 and higher. You can install the module by choosing Tools >
Update Center and downloading the module from the NetBeans Update Center.
This tutorial shows you how to add management to an existing application (the
NetBeans sample Anagrams Game application). You will first create a non-manageable
Anagram Java Project. You will then use JMX Wizards to generate 90% of the management.
Then you will implement the management behavior specific to the application.
You will finally use the Run/Debug project with JConsole to visualize the Anagram
MBeans.
Prerequisites
This tutorial assumes you have some basic knowledge of, or programming experience
with, the following technologies.
Tutorial exercises
Resources
- NetBeans help contents (Help > Help Contents > JMX). This help is
also available from Wizards.
- You can see a larger view of all the screen captures by clicking on them.
Exercise 1: Creating the Sample Anagram Project
The goal of this exercise is to create a runnable Java Project. The Anagram
game is a Swing Application. It displays a mixed-up word to the user and waits
for the user to solve the anagram.
- Choose File > New Project (Ctrl-Shift-N).
- Select the Samples > General category.
- Select the Anagram Game project.

- Click Next. The Project Name and Location panel is displayed. Keep
the default values.

- Click Finish. A new anagrams project is created.
Exercise 2: Creating the Anagram JMX Standard MBean
The goal of this exercise is to create a JMX Standard MBean that allows you
to monitor the time spent by the user to solve a new anagram. Each time an anagram
is solved, a JMX notification is sent.
The MBean contains :
- An Attribute named LastThinkingTime that contains the time spent
to solve the last anagram.
- An Operation named resetAll. LastThinkingTime and NumResolvedAnagrams
are set to 0.
- A notification of type AttributeChangeNotification. This notification
is emitted when LastThinkingTime is updated.
Steps to Follow
Be sure to have selected the anagrams project and to have set it as your main
project.
- Choose File > New File (Ctrl-N).
- From the Management category, select JMX MBean and click Next. The MBean
Name and Location panel is displayed.

- Enter the following information and click Next:
- Class Name: AnagramsStats
- Location: Source Packages (default)
- Package: com.toy.anagrams.mbeans

- In the Type and Options page of the wizard, select Standard MBean as the
MBean type. Add an MBean description (for example, Monitoring and Management
of the Anagrams Game). Then click Next.

- In the Attributes and Operations page, specify the MBean Attributes. Click
the Add Attribute to add an Attribute row. Then specify the following information:
- Attribute Name: LastThinkingTime
- Type: int
- Access: ReadOnly
- Description: Time needed to solve

- Click Next.
- Adding an operation is done the same way by clicking on the Add Operation
button. Add an operation named resetAll that returns void, has no
parameters, no exceptions, and which has a description of reset MBean
state. Then click Next.

- In the MBean Notifications, configure the way the current MBean will handle
notifications:
- Check the Implement NotificationEmitter Interface checkbox.
- Check the Generate Delegation to Broadcaster checkbox. All methods
declared by the NotificationEmitter interface will be implemented
by delegating to a notification broadcaster. A notification broadcaster
simplifies the way the MBean will send notifications.
- Check the Generate Private Seq Number and Accessor. Some code will be
generated to handle the unique sequence number value that must be added
to each notification that is sent.
- Add a notification by clicking on the Add Notification button. Change the
Notification Class to be javax.management.AttributeChange using the
drop-down list. Notice that the Notification Type is automatically set to
ATTRIBUTE_CHANGE. This notification is sent each time an Anagram
is solved. Set the description to Anagram is Solved.

- The steps needed to create your MBean are now finished. Clicking Next allows
you to generate a JUnit test, but we will not do this just yet. However, we
will do it later. So, skip the last step and generate the MBean now by clicking
on Finish.
The AnagramsStats MBean class and interface are generated in the anagrams
project. Looking at the members view and at the generated code, you will notice
that the getLastThinkingTime method is generated in the AnagramsStats
class and in the AnagramsStatsMBean interface. A private field named
lastThinkingTime of type int is also generated. It is used to store
the attribute value.

Summary
In this exercise, you have learned how to create an MBean using the MBean wizard.
Exercise 3: Updating the AnagramsStats MBean
Creating an MBean is generally an iterative task. You first generate an MBean
with a set of Attributes and Operations, then you add/remove some. In this exercise
we are going to add the attribute NumSolvedAnagrams to the MBean we
generated previously.
Steps to Follow
- In the Projects tree, select the AnagramsStats node.
- Chosose Management > Add Attributes from the main menu. You can also
access this contextual menu by right clicking on the selected node. Notice
that you can also add some operations, generate a JUnit test, and much more.
- The Add MBean Attributes dialog box is displayed. Notice that the LastThinkingTime
attribute you defined above is displayed in the list of attributes.
- Add the new attribute in exactly the same way as you did using the MBean
Wizard:
- Click Add Attribute.
- Enter NumSolvedAnagrams as the attribute name.
- Set the type to int.
- Set the access to ReadOnly.
- Enter Number of solved anagrams as the attribute description.

- Click OK. The method getNumSolvedAnagrams is added at the end of
the AnagramsStats and AnagramsStatsMBean classes. A private
field named numSolvedAnagrams of type int is added at the
top of AnagramsStats class. It is used to store the attribute value.
- The MBean is now updated with the new attribute. We will now add some logic
to the MBean.
Exercise 4: Implementing the AnagramsStats MBean
In this exercise, we will add some management logic to the AnagramsStats
class.
Steps to Follow
- First, notice that the attributes NumSolvedAnagrams and LastThinkingTime
are already implemented. They don't need any updates.
- The resetAll method needs to be implemented. The generated body
is empty. When resetAll is called, we simply set both counters
to 0. Add the following code in the resetAll method body:
lastThinkingTime = 0;
numSolvedAnagrams = 0;
- Add some methods to the AnagramsStats class in order for the Anagrams
UI class to notify the MBean that a new anagram has been proposed to the user,
or that an anagram has been solved. Add some code to create and send a notification
when an anagram is solved. Click
here for the code to add to AnagramsStats class.
- Notice that a JMX notification of type ATTRIBUTE_CHANGE is sent
each time an anagram is solved. The next figure shows the updated AnagramsStats
class.

- You are done with the MBean implementation. Now we will generate a JUnit
test then add some testing logic.
Summary
In this chapter you learned how to implement a Standard MBean. This is done
in two phases. First you implement the management Attributes and Operations,
then you add methods to allow MBean state updates.
Exercise 5: Generating a JUnit Test for the AnagramsStats
MBean
In this exercise, you will learn how to generate a JUnit test for an MBean.
This generates a set of tests based on the MBean attributes and operations.
With these special JUnit tests, you will not deal with the MBean deployment.
You will only focus on testing the MBean Attributes and Operations.
Steps to Follow
- In the Projects tree, select the AnagramsStats node.
- Choose Management > Create JUnit Test form the main menu. You can also
access this contextual menu by right clicking on the selected node. The Create
JUnit Test dialog box is displayed.

The created file com.toy.anagrams.mbeans.AnagramsStatsTest will
be generated in the Test packages. A list of MBean constructors is proposed.
The constructor you select will be used to instantiate the MBean before registering
it in the MBean server. If you need to provide some parameters to your
MBean, you will have to update the generated createMBean method.
- Keep the default values and click OK. AnagramsStatsTest opens in
the Source Editor.

Summary
In this exercise you learned how to create a JUnit test class for an MBean.
Exercise 6: Adding Logic to the JUnit AnagramsStatsTest
Class
In this exercise, you will learn how to add logic to a JMX JUnit test and how
to run the test. You will add a simple assertion in each test case.
Steps to Follow
- For each Attribute, a method named testattribute_NameAttribute
is generated. In this method, the attribute is obtained. We will then add
some to test the returned value.
- In the method testLastThinkingTimeAttribute, replace the
call to fail("The test case is empty"); with assertTrue("The
Last Thinking Time must be equals to 0", val == 0);
- In the method testNumSolvedAnagramsAttribute replace the
call to fail("The test case is empty"); with assertTrue("The
Num of Solved Anagrams must be equal to 0", val == 0);

- For each Operation, a method named testoperation_NameOperation
is generated. In this method, the operation is called. We will then add some
logic to test that no exceptions were thrown.
- In the method testResetAllOperation replace the call to
fail("The test case is empty"); with assertTrue("Method invoked
successfully", true);

- Run the JMX JUnit test. Select the com.toy.anagrams.mbeans.AnagramsStatsTest
class in Test packages. Right click, then select Run File in the popup menu.
Test results are displayed in the JUnit Test Results window.

Summary
In this chapter, you learned how to update and run JMX JUnit tests. Now that
we have an MBean, we need to create a container to deploy it. This is the role
of the JMX Agent.
Exercise 7: Generating a JMX Agent
In this exercise, you will learn how to generate a JMX Agent. An agent is a
simple runnable or non-runnable class that:
- Provides a method to create and register your MBeans.
- Provides access to the MBean server.
- Provides a singleton design pattern that allows you to easily access an
initialized agent. An initialized agent is an agent that has all its MBean
registered.
Note: A runnable Agent (one that contains a main method) is generated when you
want to create a management application. Non-runnable agents are used when you
want to add management to an application. This tutorial shows the latter of these
agents. We will add management to the Anagrams game, which already has a main
runnable class.
You will also learn how to add an MBean to an Agent and how to make the MBean
accessible from the agent.
Steps to Follow
- Choose File > New File (Ctrl-N).
- Select the JMX Agent template from the Management category and click Next.

- In the Name and Location page, type JMXAgent as the Class Name.
Set com.toy.anagrams.agent for the Package. Unselect the Create Main
Method checkbox. (In this tutorial we are instrumenting an application that
already has a main.) Then click Finish.

- The JMXAgent class is generated in your project. The JMXAgent
class is opened in the editor pane. Note the init method and its
commented sample code that shows you how to manually register an MBean.
Exercise 8: Adding the AnagramsStats MBean to the
Agent
In this exercise, you will learn how to add an MBean to a JMX Agent. Adding
an MBean to an Agent involves:
- Instantiating the MBean
- Naming the MBean
- Registering the MBean in the MBeanServer
This module provides you with a utility that handles these tasks.
Info
Best practices when naming your MBeans :
- When naming your MBean, we encourage you to use the key type. The value
of this key should be the MBean class (in our case AnagramsStats).
- In the case of a singleton MBean (an MBean that has a single instance within
your application), having this unique key is sufficient for naming purposes.
- We also encourage you not to create too many naming domains. You can reuse
default domain names. Not specifiing a domain before the ObjectName
: is an implicit reference to the default naming domain.
Applying best practices will make the way you name your MBeans more formalized.
The ObjectName we are creating is :type=AnagramsStats.
Steps to Follow:
- In the Projects tree, select the JMXAgent node.
- Choose Management > Instantiate and Register MBean from the main menu.
The Instantiate and Register MBean dialog box is displayed.

- Click the Browse button to select your MBean. The current project tree is
displayed.
- Select Source Packages > com.toy.anagrams.mbeans > AnagramsStats.

- Click OK. The dialog box is updated with the MBean you selected. The MBean
ObjectName is computed automatically. The discovered MBean constructors
are displayed.

- Keep the default values and click OK. The JMXAgent init
method is updated with the MBean registration code.

- In the context of this tutorial, an extra step is required. We want the
application to have access to the class implementing the management interface
(AnagramsStats). This is not a general rule but it can be useful
when your application needs to push data to an MBean. The startThinking
and stopThinking methods are used by the application to notify the
MBean that some events have occured. In turn, the MBean updates its state.
In order to make AnagramsStats accessible from the Anagrams
UI class, we need to modify the init method and add an MBean accessor
to the agent. The following image shows the parts of the JMXAgent
class that must be updated (click on the image for a larger view).

You have finished your agent instrumentation. We are now going to connect
the anagrams game and the JMX management layer together.
Summary
In this chapter you learned how to instrument a JMX Agent. Mainly. You added
MBean creation and registration code to the init method. You also provided
accessors to provide local access to the MBean.
Exercise 9: Connecting Management and the Application
Together
In this exercise, you will learn how to access the MBean from the application
and how to implement the management logic. This is very simple and can be achieved
with just a few lines of code.
Steps to Follow:
- Double-click the Anagrams UI main class in the com.toy.anagrams.ui
package. The class opens in the IDE's Design view.
- Click Source at the top of the Source Editor to edit the class in the Source
view.
- Add a call to the initManagement method in the Anagrams class constructor.
- Implement an initManagement private mehod.
- Access the JMXAgent singleton instance. This will have the side
effect of registering the AnagramsStats MBean.
- Access the AnagramsStats MBean and call startThinking()
on it. When the anagrams game is first displayed, an anagram is displayed.
So we need to compute the time at the very beginning of the application's
execution.
- We now need to add code to track the user's anagram solving experience.
Add code in 2 places:
- Each time a new anagram is proposed to the user, we must compute the start
time. This is done in the nextTrialActionPerformed method.
- Each time an anagram is guessed correctly, we need to notify the MBean
that the thinking time is over. This is done in the guessedWordActionPerformed
method.

You are have finished linking the JMX layer to the application layer. We
are now going to execute the application and play a little bit with the Anagrams
game.
Exercise 10: Running the Application with JConsole
In this exercise, you will learn how to compile, run your project, and connect
JConsole to visualize the JVM state, as well as the application MBeans.
Steps to Follow
- A single step performs all these tasks. Click the Run with JConsole icon
in the toolbar.
- A dialog box warns you that the build.xml files will be updated.
Just click OK.
You can follow the execution in the output console.
- The Anagram game is displayed. Don't click on guess right now. First set
up JConsole to display information.
- JConsole is displayed. Select the MBeans tab.
- Select the AnagramsStats MBean, then select the Notifications tab.
- Subscribe to notifications. JConsole will receive a new notification each
time an anagram is solved.
- Go back to the Attributes tab and double-click the LastThinkingTime
value to plot the thinking time.
- In the Anagrams window, solve the first anagram (It is easy, but I'll give
you the first answer: abstraction).
- Notice that the attributes are updated and that JConsole received a notification.
You can select the Notifications tab to visualize the notification details.
- Don't forget that we added a management operation resetAll. You
can access MBean Operations by selecting the Operations tab. You then have
to click the resetAll button. Notice that the MBean attribute values
changed to 0.
Yes! You are done! You did a really good job.
I hope that this tutorial helped you understand how to add management to your
application. You should be able to apply what you learned to your development.