Sie sind auf Seite 1von 31

Cache Monitoring Tool

USN: 1MJ09MCA08

1. Introduction:

In this project we need to view and monitor the cache details (using a Web console) to study the data access trends for objects stored in the cache and determine which objects were better used by storing them in the cache instead of directly going to backend data store. We wanted to use the Java Management Extensions (JMX) technology for this requirement, but didn't want to change any existing application code because we were not sure how much overhead the monitoring code would add. We decided to use Log4j for storing the history and techniques to dynamically introduce JMX code into existing Java classes and get the cache statistics that way. That way, if the monitoring overhead turned out to require too much overhead, we could easily unweave the JMX code from the application code, returning it to the exact state it was in prior to introducing the monitoring logic. Good monitoring practices are a vital part of an overall strategy for keeping our systems healthy. While Cache is largely self-regulating when properly installed and configured, unforeseen events can happen. Cache provides a suite of tools, processes and APIs for the real-time monitoring necessary to keep watch on Cache appropriately.

An effective monitoring process looks not only at Cache, but the application, the operating system, the network, the storage system, and the hardware. While the focus of this document is Cache, these other areas need to be part of our comprehensive approach to monitoring.

Cache includes monitoring utilities and services that are ready to use. This may be sufficient for many applications with only some simple setup required. For sites requiring integration with existing tools or products, or applications that need more sophisticated monitoring processes, Cache provides the framework, APIs and system classes to build custom, powerful and integrated solutions.

Department of MCA

Cache Monitoring Tool

USN: 1MJ09MCA08

1.1 System Architecture:

Runtime servers RS1

JSON

Monitoring agent

REST/JSON JVM RS2 HTTP

HTTP

Monitoring server HTTP HTTP

Console

REST/JSON RS3 HTTP

Reference cache JoLokia JMX

REST/JSON

REST/JSON

HTTP

RS40 Platform MBeanServer JDBC Log4J

DB Access logger

Memory cache

Department of MCA

Cache Monitoring Tool

USN: 1MJ09MCA08

JMX: This technology provides a simple, standard way of managing resources such as application, devices, and services. Because the JMX technology is dynamic, we can use it to monitor and manage resources as they are created, installed and implemented.

Log4j: Log4j API is an Apache project. It provides you the logging mechanism. Which allows you to direct the debug & error (basically) statements onto a particular file/database/messaging system etc. It provides a much cleaner way to store the output statement during the program execution. It can record information up to a class level. For ex: You have X, Y, Z ...N classes....lets say Z classes has thrown and exception/error which you logged using Log4j, while finding the root cause you would see those error/debug files...It will show you the absolute class name as well, if configured so.

JSON: JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for
humans to read and write. It is easy for machines to parse and generate.

It is language independent. It implements communication protocol. It represents configuration information.

Platform MBeanServer: An MBean server is a repository of MBeans that provides management applications access to MBeans. Applications do not access MBeans directly, but instead access them through the MBean server with their unique ObjectName. An MBean server implements the interface javax.management.MBeanServer. We can also create our own MBean server using the MBeanServerFactory class. Reference cache: This is a table which maps objects in memory to their internal id. The internal id is used to find the object on disk. This table has a reference to the object in memory it also acts as cache. Therefore it's called reference cache.

Department of MCA

Cache Monitoring Tool

USN: 1MJ09MCA08

2. Literature survey:
2.1 Existing system:
In the last decades both processor and memory speedup have been growing at an exponential rate. However, the growth rate of the memory speedup has been significantly lower than the one of that could be observed for processor speeds, leading to a significant and continuously growing gap. This problem, often referred to as the memory wall, has a severe impact on modern micro processors, as they cannot fully exploit their potentials as the memory access acts as severe bottlenecks and prohibits a sufficient stream of data and instructions.

3. Problem definition:
3.1 Proposed solution:

In this project we need to view and monitor the cache details (using a Web console) to study the data access trends for objects stored in the cache and determine which objects were better used by storing them in the cache instead of directly going to backend data store. We wanted to use the Java Management Extensions (JMX) technology for this requirement, but didn't want to change any existing application code because we were not sure how much overhead the monitoring code would add. We decided to use Log4J for storing the history and techniques to dynamically introduce JMX code into existing Java classes and get the cache statistics that way. That way, if the monitoring overhead turned out to require too much overhead, we could easily unweave the JMX code from the application code, returning it to the exact state it was in prior to introducing the monitoring logic.

Department of MCA

Cache Monitoring Tool

USN: 1MJ09MCA08

3.2 Advantages of proposed solution:

Reduce load on Web Services/ Database Increase Performance Reliability (Assuming db backed cache. Server goes down and db is backed by cache

there is no time wasted to repopulate an in memory cache)

4. System Requirement Specification:


4.1 Purpose and scope:
We can store any type of data in the cache, but the benefits increase when the data is accessed frequently and when it takes more time and resources to retrieve the data from the source, such as a database, than from the cache. When the cache is being used to store different types of data, cache monitoring becomes an important task from several different points of view. Because we need to:

Know how objects in the cache get cleaned up on a regular interval. Verify that objects stored in the cache are not taking too much memorywhich could cause performance problems in the application.

Detect when the cache size grows beyond a maximum allowed threshold and raise any alerts to clean up the cache.

Department of MCA

Cache Monitoring Tool

USN: 1MJ09MCA08

4.2 Functional requirement:


It should provide a GUI based administration console for monitoring and managing the object cache with the ability to view and edit cache behavior. It should notify appropriate individuals or groups when exceptions are thrown when storing and purging the data stored in the cache. It should provide the ability to expire the cached data on demand (via a Web-based JMX console).

4.3 Data store requirement:


In HSQLDB we will create table like Cache and the attributes will be like below Cache_type, Instance_name, Error, Warning, Instance_ip, Message, Last_modified_date

CREATE TABLE Cache ( Cache_type CHAR(10), Instance_name CHAR(10), Error CHAR(10), Warning CHAR(10), Instance_ip CHAR(10), Message CHAR(20), Last_modified_date DATE );

Department of MCA

Cache Monitoring Tool

USN: 1MJ09MCA08

4.4 Technology requirement:

Hardware requirements: HDD: 300GB RAM: 2GB

Software requirements: Operating system: WindowsXp or above, Linux Programming Language: Java Frameworks: Spring, JSP, JDBC Backend: HSQLDB

5. Work done:

Created our own database using HSQLDB and with the help of Java Bean, JSP, XML we have monitored the error and warning for every server. And also with the help of springs, JSP, XML we have monitored the error and warning for every server.

Department of MCA

Cache Monitoring Tool

USN: 1MJ09MCA08

6. Work to be done:
Get the Version Comparison Result Object which has the entire information that has to be stored in the table. Check the number of the records and the number of the current record fields from this object. If the current object is the 1st object in the list of size m, then delete all the existing records from the table and insert the values in the object into the table. If the current object is the nth object in the list of size m and n<=m, then insert the objects values directly into the table.

Department of MCA

Cache Monitoring Tool

USN: 1MJ09MCA08

7. Conclusion:
The data is accessed frequently and when it takes more time and resources to retrieve the data from the source, such as a database, than from the cache. When the cache is being used to store different types of data, cache monitoring becomes an important task from several different points of view. So with this project we can monitor every server information, and can also inform to the administrator regarding the error and warnings occurred in the particular server.

Department of MCA

Cache Monitoring Tool

USN: 1MJ09MCA08

8. Reference:
www.enigmaticsoftware.com/cachemonitor/index.html www.ehcache.org/documentation/operations/jmx www.cachemonitor.de/cache-monitor-support/blog www.cachemonitor.de/cache-monitor/faq-about-cache-monitor-with-intersystems-cache www.roseindia.net/spring/springhsqldbexamples

Java

the

Complete

Reference,

Seventh

Edition

Herbert,

McGraw-Hill

Professional, 2006 J2SE 5th Edition- Herbert Schildt,TATA McGraw-Hill, 2007 J2EE-Jim Keogh, Complete Reference, TATA McGraw-Hill, 2007

Pronounced cash, a special high-speed storage mechanism. It can be either a reserved section of main memory or an independent high-speed storage device. Two types of caching are commonly used in personal computers: memory caching and disk caching. A memory cache, sometimes called a cache store or RAM cache, is a portion of memory made of high-speed static RAM (SRAM) instead of the slower and cheaper dynamic RAM (DRAM) used for main memory. Memory caching is effective because most programs access the same data or instructions over and over. By keeping as much of this information as possible in SRAM, the computer avoids accessing the slower DRAM. Some memory caches are built into the architecture of microprocessors. The Intel 80486 microprocessor, for example, contains an 8K memory cache, and the Pentium has a 16K cache. Such internal caches are often called Level 1 (L1) caches. Most modern PCs also come with external cache memory, called Level 2 (L2) caches. These caches sit between the CPU and the DRAM. Like L1 caches, L2 caches are composed of SRAM but they are much larger. Disk caching works under the same principle as memory caching, but instead of using highspeed SRAM, a disk cache uses conventional main memory. The most recently accessed data from the disk (as well as adjacent sectors) is stored in a memory buffer. When a program needs to access data from the disk, it first checks the disk cache to see if the data is there.

Department of MCA

10

Cache Monitoring Tool

USN: 1MJ09MCA08

Disk caching can dramatically improve the performance of applications, because accessing a byte of data in RAM can be thousands of times faster than accessing a byte on a hard disk. When data is found in the cache, it is called a cache hit, and the effectiveness of a cache is judged by its hit rate. Many cache systems use a technique known as smart caching, in which the system can recognize certain types of frequently used data. The strategies for determining which information should be kept in the cache constitute some of the more interesting problems in computer science.

Managing Bean Example


This section describes you the use of the managed bean in an JSF application. In an JSF application, backing beans (managed beans) are used that can be associated with UI components. Backing Beans are nothing but JavaBeans which defines properties and methods. These properties are bound to component values or component instances. setX() and getX() methods are defined and implemented for all properties. We can also define methods that can be used for different purpose like event handling, navigation, validation etc. that are associated with component. To bind value of the component to the property of the bean or to refer method of the bean from component tag, Expression Language (EL) syntax is used. For example, #{BeanName.propertyName}can be used to bind the value of the component to the property "propertyName" of the bean "BeanName". #{BeanName.methodName} can be used to refer method "methodName()" of the bean "BeanName". This tutorial explains how backing bean can be used in our application "managedbean". In this application "Bean.java" is backing bean which has been used further in view pages. We have saved this JavaBean file in WEB-INF\classes\roseindia directory of this application. Step1 : Create a JavaBean file "Bean.java".
package roseindia; public class Bean{ private String thought_of_the_day; private String userName; private String phoneNo; private String company; public void setThought_of_the_day(String thought_of_the_day){ this.thought_of_the_day=thought_of_the_day; } public void setUserName(String userName){ this.userName=userName; } public void setPhoneNo(String phoneNo){ this.phoneNo=phoneNo; } public void setCompany(String company){

Department of MCA

11

Cache Monitoring Tool


this.company=company; } public return } public return } String getThought_of_the_day(){ thought_of_the_day; String getUserName(){ userName;

USN: 1MJ09MCA08

public String getPhoneNo(){ return phoneNo; } public String getCompany(){ return company; } public String selectPage(){ if(company.equals("RoseIndia")){ return "rose"; } else{ return "other"; } } }

In the above file, there are four properties "thought_of_the_day", "useName", "phoneNo", "company" and setter and getter methods for each property to get and set values for the components respectively . There is one more method selectPage() that returns "rose" and "other" strings according to the condition. Step2 : Configure the configuration file "faces-config.xml". Just add lines given below in this file. To configure the bean in configuration file <managed-bean> element is used. Its child element <managed-bean-name> is used to give the name of the bean to be used in the application to refer the bean class specified in another child element <managed-bean-class>. We can also specify the property value in the configuration file. For this <managed-property> child element is used where its child element <property-name> specifies the name of the property and <value> specifies its value. <managed-bean> <managed-bean-name>Bean</managed-bean-name> <managed-bean-class>roseindia.Bean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> <managed-property> <property-name>thought_of_the_day</property-name> <value>It's good to be important but it's more important to be good. </value> </managed-property> </managed-bean> For navigation purpose add following lines to the configuration file.

Department of MCA

12

Cache Monitoring Tool <navigation-rule> <from-view-id>/pages/user.jsp</from-view-id> <navigation-case> <from-outcome>rose</from-outcome> <to-view-id>/pages/welcome.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>other</from-outcome> <to-view-id>/pages/otherpage.jsp</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <from-view-id>/pages/welcome.jsp</from-view-id> <navigation-case> <from-outcome>Edit</from-outcome> <to-view-id>/pages/user.jsp</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <from-view-id>/pages/otherpage.jsp</from-view-id> <navigation-case> <from-outcome>back</from-outcome> <to-view-id>/pages/user.jsp</to-view-id> </navigation-case> </navigation-rule>

USN: 1MJ09MCA08

Step3 : Now we are ready to create view pages and use bean properties and methods in the application . In this example, we have three JSP pages "user.jsp", "welcome.jsp", "otherpage.jsp" in the "pages" directory within the application home directory. user.jsp : <%@taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <html> <head><title>Managed Bean Example(User Page)</title></head> <body> <f:view> <h:form> &nbsp;&nbsp;<h:outputText value="User Name." /><br> &nbsp;&nbsp;<h:inputText value="#{Bean.userName}"/><br><br> &nbsp;&nbsp;<h:outputText value="Phone No." /><br> &nbsp;&nbsp;<h:inputText value="#{Bean.phoneNo}" /><br><br> &nbsp;&nbsp;<h:outputText value="Company Name" /><br> &nbsp;&nbsp;<h:inputText value="#{Bean.company}" /><br><br> &nbsp;&nbsp;<h:outputText value="Thought of the day" /><br> &nbsp;&nbsp;<h:inputText value="#{Bean.thought_of_the_day}" /> <h:commandButton value="Submit" action="#{Bean.selectPage}" /> </h:form>
Department of MCA 13

Cache Monitoring Tool </f:view> </body> </html>

USN: 1MJ09MCA08

In this page we have associated values of the UIcomponents to the backing bean's properties. This binding has been shown by bold letters. userName, phoneNo, company, thought_of_the_day properties are bound to the input components. When the user first calls this page, the last input component will be shown with the value specified in the "facesconfig.xml" file because we have already specified this value in the configuration file. When the user fills values in these components these values are stored in the properties of the bean. So when they are again bound with the component, stored values are used. For example, in "welcome.jsp" page we have again used these properties values so it considers the values filled in previous page. Command button component's action is associated with selectPage() method of the Bean class. This method returns a String value either "rose" or "other". This value is set to the action attribute of the commandButton tag. This button works according to the returned value and the navigation rules specified in the "faces-config.xml" file. welcome.jsp : <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <html> <head><title>Managed Bean Example (Welcome page)</title></head> <body> <f:view> <h:form> <h:outputText value="You have entered :" /><hr>User Name : <h:outputText value="#{Bean.userName}" /><br> Password : <h:outputText value="#{Bean.phoneNo}" /><br> Phone No : <h:outputText value="#{Bean.company}" /><br> <h:commandButton value="Edit Details" action="Edit"/><hr> <h:outputText value="#{Bean.thought_of_the_day}" /></b> </h:form> </f:view> </body> </html> otherpage.jsp : <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <html> <head><title>Managed Bean Example (otherpage page)</title></head> <body> <f:view> <h:form> <h:outputText value="Sorry........This is for RoseIndia

Department of MCA

14

Cache Monitoring Tool employees only. " /><br> <h:commandButton value="Go Back" action="back"/> </h:form> </f:view> </body> </html>

USN: 1MJ09MCA08

Output : This is the first page which has four input boxes and one submit button. Last input box already contains some text which comes from the value specified in the configuration file.
Using Management Factory:

An application can directly call the methods of a platform MBean running in the same Java virtual machine. To do so, use the static methods of the ManagementFactory class. Management Factory has accessor methods for each platform MBean such as getClassLoadingMXBean(), getGarbageCollectorMXBeans(), getRuntimeMXBean(), and so on. In the cases where there are more than one platform MBean, the method returns a List of platform MBeans. For example, the following code uses the static method of ManagementFactory to get the platform MBean RuntimeMXBean, and then gets the vendor name from the platform MBean:
RuntimeMXBean mxbean = ManagementFactory.getRuntimeMXBean(); String vendor = mxbean.getVmVendor();

Monitoring Thread Contention and CPU Time


The ThreadMXBean platform MBean provides support for monitoring thread contention and thread CPU time. The Sun HotSpot JVM supports thread contention monitoring. Use the ThreadMXBean.isThreadContentionMonitoringSupported() method to determine if a JVM supports thread contention monitoring. Thread contention monitoring is disabled by default. Use the setThreadContentionMonitoringEnabled() method to enable it. The Sun HotSpot JVM supports measuring thread CPU time on most platforms. The CPU time provided by this interface has nanosecond precision but not necessarily nanosecond accuracy. Use the isThreadCpuTimeSupported() to determine if a JVM supports measuring of the CPU time for any thread and isCurrentThreadCpuTimeSupported() to determine if a JVM supports measuring of the CPU time for the current thread. A Java virtual machine implementation that supports CPU time measurement for any thread will also support that for the current thread. A JVM may disable thread CPU time measurement. Use the isThreadCpuTimeEnabled() method to determine if thread CPU time measurement
Department of MCA 15

Cache Monitoring Tool

USN: 1MJ09MCA08

is enabled . Use the setThreadCpuTimeEnabled() method to enable/disable this thread CPU time measurement.

About JMX and MBeans JMX stands for Java Management Extensions, and is a facility to allow for remote clients to connect to a JVM, and manage/monitor running applications in that JVM. This management is typically done through MBeans. MBeans are the heart of the JMX specification. For an application developer, MBeans are the controllable endpoints of your application where remote clients can observe application activity as well as control the inner workings. Like any good application design, determining how your mbeans should be structured and designed is not an exact science, but they also aren't nearly as scary as most people think. Writing our First MBean MBeans are actually quite easy to write. Before getting into the nitty gritty details of what you can and can't do with MBeans however, let's jump straight in. Let's pretend for the moment we have an performance-critical cache in our application. To illustrate this cache, I've implemented a little demonstration class that really has no useful cache semantics at all, but gets the job done:
public class ApplicationCache { private int maxCacheSize = 100; private List cache = new ArrayList(); public synchronized void clearCache() { cache.clear(); } public synchronized int getCachedObjects() { return cache.size(); } public synchronized int getMaxCacheSize() { return maxCacheSize; } public synchronized void setMaxCacheSize(int value) { if(value < 1) { throw new IllegalArgumentException("Value must be >= 1"); } maxCacheSize = value; } public synchronized void cacheObject(Object o) { while(cache.size() >= maxCacheSize) { cache.remove(0); } cache.add(o); } }

Department of MCA

16

Cache Monitoring Tool

USN: 1MJ09MCA08

Like I said, it's fairly simple, but it gets the job done. Now, let's extract the majority of this API out into an interface - good programming practices and all:
public interface ApplicationCacheMBean { int getMaxCacheSize(); void setMaxCacheSize(int value); int getCachedObjects(); void clearCache(); }

Now, let's change our cache class to implement the interface:


public class ApplicationCache implements ApplicationCacheMBean {

Voila! We have just written our first MBean. No, surely it can't be that easy. Well, yes, yes it is. Exposing our MBean The next step is to tell the guts of the JMX infrastructure about our MBean so that it can be properly published to clients. This isn't a particularly difficult task. It simply involves coming up with a name for your mbean (which we already have), and a categorization for your mbean. We combine these two into a unique name for when we register the bean. Let's take a look at the code:
ApplicationCache cache = new ApplicationCache(); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName("org.javalobby.tnt.jmx:type=ApplicationCacheMBean"); mbs.registerMBean(cache, name);

Not too complicated, is it? In this case we create an identifier (the ObjectName ) for our MBean, and we register it on the platform mbean server. That is it. No really, that is it! To demonstrate how this cache can be manipulated via JMX tools, I've created a full bootstrap class that imitates some application activity by periodically adding elements to the cache:
package org.javalobby.tnt.jmx; import java.lang.management.ManagementFactory; import javax.management.*; public class JMXTest { public static void main(String[] args) throws Exception { ApplicationCache cache = new ApplicationCache(); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName("org.javalobby.tnt.jmx:type=ApplicationCacheMBean"); mbs.registerMBean(cache, name); imitateActivity(cache); } private static void imitateActivity(ApplicationCache cache) {

Department of MCA

17

Cache Monitoring Tool


while(true) { try {

USN: 1MJ09MCA08

cache.cacheObject(new Object()); Thread.sleep(1000); } catch(InterruptedException e) { } } } }

Working with JConsole MBeans are deployed to the standard platform server, so from an application *development* perspective, you don't need to worry about how external clients interact with them. That being said, the *deployment* to manage the remote protocols for your mbeans may vary from case to case. To show how our mbeans work, I'm going to point you to Java 5's standard JConsole. JConsole's documentation describes (or links to documentation that describes) how to make your application publish MBeans so JConsole can consume them. Way back when, Romain Guy discussed some bits of JConsole right here on Javalobby. In this case I'm going to simply use Sun's JVM argument that publishes the platform mbean server to your local environment for monitoring. Clearly, if you were working across network boundries, you will probably need to take alternative steps. To make an application visible to JConsole, simply add this JVM argument to the startup:
-Dcom.sun.management.jmxremote

So, for example java -Dcom.sun.management.jmxremote org.javalobby.tnt.jmx.JMXTest

JConsole is an executable in the bin for your Java 5 JDK. The Results Once I have started JConsole and my test application, I see this prompt inside JConsole:

Department of MCA

18

Cache Monitoring Tool

USN: 1MJ09MCA08

I select this application to monitor, and once JConsole opens I select the 'MBeans' tab. Immediately, I see our new mbean listed on the left! I select it, and am presented with this page:

Department of MCA

19

Cache Monitoring Tool

USN: 1MJ09MCA08

Now the fun begins. First, let's try changing our max cache size. You'll notice that the cache size is in blue, which in JConsole terms means that is is modifiable. Clicking on the field makes it editable. Here you can see I changed it to 50:

Let's see what happens if we change the value to zero - if you notice in the code above, we don't allow this value to be below 1:

It has translated our exception into an error dialog! Now let's change to the operations tab:

There is our clear cache method! Pushing it has the effect you'd expect on the cache size:

Disclaimer At this point, those of you who have gotten your fix and want to go play with mbeans, by all means do. I'm going to now explain some of the boundries and definitions of the mbeans. The Format of MBeans MBeans have primarily three components: attributes , operations and notifications . As you can probably guess by our tour through JConsole, attributes are values that are

Department of MCA

20

Cache Monitoring Tool

USN: 1MJ09MCA08

defined via getters/setters in your API. Setters are optional, as seen by our getCachedObjects() method, which, by JConsole's interpretation is read only. Operations are methods like clearCache() which are assumed by the MBean spec to be behavioral methods. I haven't addressed notifications yet; they'll be time for that in the future though. On Data Types One of the key restrictions of MBeans is data types. For the most part, MBeans work in the world of primitive values (booleans, ints, etc), Strings, and arrays of any of the preceding. It is possible to use more complex data types (and there are varying approaches to this), but those are out of the scope of this tip. Besides, I've found that well over 80% of the time the default data types work just fine. On Methods As I mentioned above, methods on an MBean are either considered operations or attributes. Attributes are properties bound with getter (and potentially) setter methods, with the convention being a 'get' prefix. Any other methods are simply considered operations. Attributes must follow standard getter/setter conventions (getters have a non-void return type, and no arguments, setters have a void return type, and a single argument of type matching the corresponding getter's return type). Operations may have any number of arguments, and may have a return type (or may not). On Exceptions Any method in an mbean is allowed runtime and checked exceptions to be thrown. They are expected to be handled by the MBean client. On Interfaces One of the pieces we made in our whirlwind tour was the interface. Strictly speaking, for programs like JConsole, the interface isn't necessary. On the other hand, the interface is very helpful when writing client code to call back into JMX. Why? Because JMX can create dynamic proxies via the interface to allow you to work directly with the class:
MBeanServer server = ObjectName name = new ObjectName("org.javalobby.tnt.jmx:type=ApplicationCacheMBean"); ApplicationCacheMBean mbean = (ApplicationCacheMBean) = MBeanServerInvocationHandler.newProxyInstance(mbs, objectName, ApplicationCacheMBean.class, false); mbean.setMaxCacheSize(9000000);

On Naming Object naming is really composed of two parts - the domain, and the key-value property list. The convention looks something like this:
Department of MCA 21

Cache Monitoring Tool

USN: 1MJ09MCA08

[domain]:[key]=[value],[key2]=[value2]... Aside from the expected 'type' key, what keys and values are available is strictly up to you. Keep in mind however, that ordering of their existence is often used by MBean clients (like JConsole) to provide hierarchical representations of the MBeans. An MBean registered like this: "my.mbeans:type=Cache,realm=UI,objects=ImageHandles" may show up in a UI like this:
my.mbeans.type | *---Cache | *---UI | *---ImageHandles

The domain should not contain a colon, and should follow reasonable naming conventions. It doesn't have to be a package name, but it should be something representative of your application. Tomcat uses Catalina for instance. What's Next Some people may be frustrated that I only showed a very basic view of what JMX is capable of. There is plenty more available. Among the features still to be uncovered: notifications (listeners on your mbean), dynamic mbeans, model mbeans, complex data types (composite data, tabular data), remote connecting options, and more. I suggest checking out some further reading (below), or staying tuned in to Javalobby tips and tricks as we will surely travel some of these roads together. I simply wanted to show you that you shouldn't be afraid of JMX. The entrance fee is cheap, and the results can be invaluable for most applications. References

Using JConsole to Monitor Applications Java Management Extensions Homepage Java Management Extensions Documentation

Until next time, R.J. Lorimer


Contributing Editor Author Software Consultant -

rj -at- javalobby.org http://www.coffee-bytes.com http://www.crosslogic.com

11 replies so far ( Post your own) 1 . At 4:10 AM on Sep 28, 2005, Alarmnummer

wrote:

Department of MCA

22

Cache Monitoring Tool


Reply

USN: 1MJ09MCA08

Re: JMX: Getting Started With MBeans I`m not too happy with the design of your example. Maybe it is just because it is just an example and in that case my remark is only for other readers. I don`t like that your ApplicationCache implements the ApplicationCacheMBean interface. There are 2 reason: 1) an MBean could have different needs and not everything has to be accessible. 2) management is just an aspect and with your design you have made it part of the core. This is how I usually do it: public interface ApplicationCache { int getMaxCacheSize(); void setMaxCacheSize(int value); int getCachedObjects(); void clearCache(); } public interface ApplicationCacheMBean { int getMaxCacheSize(); void setMaxCacheSize(int value); int getCachedObjects(); void clearCache(); } public class StdApplicationCache implements ApplicationCache{....} public class ApplicationCacheMBeanImpl implements ApplicationCacheMBean{ private ApplicationCache _cache; public ApplicationCacheMBeanImpl(ApplicationCache cache){ _cache = cache; } public int getMaxCacheSize(){ return _cache.getMaxCacheSize(); } public void setMaxCacheSize(int value){ return _cache.setMaxCacheSize(value); Department of MCA 23

Cache Monitoring Tool


} public int getCachedObjects(){ return _cache.getCachedObjects(); } public void clearCache(){ return _cache.clearCache(); } }

USN: 1MJ09MCA08

You could compare it to local interfaces and remote interfaces. The MBean is the remote interface and the bean is the local interface. I use exactly the same design when I implement remote services for local beans. 2 . At 10:51 AM on Sep 28, 2005, R.J. Lorimer wrote: Reply Re: JMX: Getting Started With MBeans Yes, you're right - core business services should probably not implement any MBean contract directly, but rather should be adapted into one. I made the consolation simply for the example. This is described in more detail in the documentation I linked to in the references section here: http://java.sun.com/products/JavaManagement/best-practices.html#mozTocId791390 This makes a brief attempt at describing the pros and cons of making core business services mbeans. Regards, Best, R.J. Lorimer 3 . At 10:52 AM on Sep 28, 2005, Artur Biesiadowski Reply Re: JMX: Getting Started With MBeans > You could compare it to local interfaces and remote > interfaces. The MBean is the remote interface and the > bean is the local interface. I use exactly the same > design when I implement remote services for local > beans. wrote:

Department of MCA

24

Cache Monitoring Tool

USN: 1MJ09MCA08

It is a matter of personal preference. I, for example, try to have a single interface for given object, regardles if it is remote or local - I care about what object can do, not where it is placed. 4 . At 11:29 AM on Sep 28, 2005, Alarmnummer Reply Re: JMX: Getting Started With MBeans It is a matter of personal preference. I, for example, try to have a single interface for given object, regardles if it is remote or local - I care about what object can do, not where it is placed. -------------------------------------Well.. a remote interface will be different from a local interface (remote interface is coarse grained... maybe dto`s.. ) and a local interface will be much more fine grained. And you don`t want every method from your local interface in your remote interface. So there there are differences (even though in a lot of cases the differences are small). 5 . At 12:33 PM on Sep 28, 2005, Steven Nakhla wrote: Reply JMX security? This was a good introduction to JMX for me. But what about security issues? What if I had a JMX bean that I wanted only certain users to be able to access? Is there any mechanism provided for that? For example, the ability to authenticate and provide credentials in order to call a method on a JMX bean? 6 . At 1:04 PM on Sep 28, 2005, R.J. Lorimer wrote: Reply Re: JMX security? Steven, Yes, there absolutely are! These fall into the 'remoting possibilities' of JMX beans, and may vary depending on your needs; hopefully I can cover some of these in the future. For instance, the facilities for enabling the platform JMX agent are detailed here (along with username/password credential instructions): http://java.sun.com/j2se/1.5.0/docs/guide/management/agent.html#jmxagent Best, R.J. Lorimer 7 . At 1:54 PM on Sep 28, 2005, Artur Biesiadowski wrote: wrote:

Department of MCA

25

Cache Monitoring Tool


Reply Re: JMX: Getting Started With MBeans > Well.. a remote interface will be different from a > local interface (remote interface is coarse > grained... maybe dto`s.. ) and a local interface will > be much more fine grained. And you don`t want every > method from your local interface in your remote > interface. So there there are differences (even > though in a lot of cases the differences are small).

USN: 1MJ09MCA08

In many cases it is enough to have a 'official' interface with important, high-level methods ('remote' one in your terminology) and for the rest, use specific implementation class. If you really go with separate usage patterns for remote and local versions, then code is not portable between locations - and this is IMHO ugly. I suppose that you are heavily based in EJB world - where local/remote distinction was made quite strong and design is heavily based on technology peculiarities. With good framework, it is perfectly possible to have a single view of objects, independent from location. I agree that probably JMX interface should be different anyway - but because it is about metrics/configuration settings, not just because it is remote. Maybe annotations over normal interface would be enough ? (Like, 'expose this method as JMX, under this name'). 8 . At 2:07 PM on Sep 28, 2005, Alarmnummer Reply Re: JMX: Getting Started With MBeans >In many cases it is enough to have a 'official' >interface with important, high-level methods >('remote' one in your terminology) and for the rest, >use specific implementation class. There is a difference that can`t be expressed in a single interface. With a local interface you can use objects that could never be serialized for example, this could lead to very big problems if you don`t seperate the remoting aspect. There is a fundamental difference between remote en local interfaces and those can`t be unified in a single interface. >if you really go with separate usage patterns >for remote and local versions, then code is >not portable between locations - and this is IMHO ugly. You have to explain this to me. >suppose that you are heavily based in EJB world >- where local/remote distinction was made quite wrote:

Department of MCA

26

Cache Monitoring Tool

USN: 1MJ09MCA08

>strong and design is heavily based on technology >peculiarities I don`t use EJB (I event don`t like it). And remote interfaces aren`t (in most cases) dependant on technology. I can use the same remote interface for RMI/Burlap/Hessian middleware. >With good framework, it is perfectly possible >to have a single view of objects, independent >from location. If you want to see everything as remote you are correct, but you will get terrible complex applications because you can never make use of a local interface. But I have to feeling you don`t have much experience writing such applications. Have you ever heard of a 'chatty applications' for example? I would suggest reading chapter 7 'Distribution Strategies' from 'Patterns of Enterprise Application Architecture' written by Martin fowler where the difference between a local and a remote interface is explained.

onitoring the OLAP Cache


Use You can:

Monitor memory consumption of cache types (graphical and tabular) Compare cache and shared memory Monitor query memory consumption

This information gives you an overview of system performance with respect to the amount of memory used by each cache type on a given calendar day. You can compare memory consumption for multiple executions of a query cache object and determine whether this object should be placed in cache or persistence memory. The cache types are:

Cluster application server Binary large object (BLOB) application server Flat file application server

Department of MCA

27

Cache Monitoring Tool Global application server Main memory

USN: 1MJ09MCA08

Procedure

1. On the BI OLAP Status screen, choose OLAP Cache. 2. On the BI OLAP Status : OLAP Cache screen, from the BI Components area, select a SAP NetWeaver System. 3. Check the following iViews for the OLAP cache:
Memory Consumption of Cache Types

You can display the memory consumption for cache types in graphical and tabular formats. Select the relevant format from the dropdown list. Memory Consumption of Cache Types (Graphical) You can display and compare memory consumption for different cache types on a given calendar day. This iView is graphical and provides the following information: Information Memory (KB) Calendar Day Description Amount of memory used (in KB) by the cache type Date for which the snapshot of memory consumption is displayed. The date format used is day.month.year (DD.MM.YEAR). Type of cache

Cache Type

Memory Consumption of Cache Types You can display the memory consumption for different cache types on a given calendar day. This iView is tabular and provides the following information: Information Date Description Date for which the snapshot of memory consumption is displayed. The date format used is day.month.year (DD.MM.YEAR). For example, 25.09.2006. Number of swaps made from cache to persistence memory on a given calendar day Memory consumed (in KB) by cache type main memory Memory consumed (in KB) by cache type flat file application server Memory consumed (in KB) by cache type cluster application server Memory consumed (in KB) by cache type BLOB

Swap Main Memory Flat File Cluster BLOB

Department of MCA

28

Cache Monitoring Tool


Cache vs. Shared Memory Monitor

USN: 1MJ09MCA08

In this iView, you can: Compare the amount of shared and cache memory that is available for use and the maximum amount that can be used. Display the number of entries in shared and cache memory.

This iView is graphical and provides the following information: Memory Consumption of Cache vs. Shared Memory Information Memory (KB) Calendar Day Maximum Shared Mem. Free Shared Memory Maximum Cache Memory Free Cache Memory Description Amount of memory used (in KB) by the query cache object Current date of the snapshot of memory consumption. The date format used is day.month.year (DD.MM.YEAR). Maximum amount of shared memory (in KB) that can be used Amount of shared memory (in KB) that can be used. This is the difference between the maximum shared memory available and the shared memory used. Maximum amount of cache memory (in KB) that can be used Amount of cache memory (in KB) that can be used. This is the difference between the maximum cache memory available and the cache memory used.

Entries of Cache vs. Shared Memory Information Maximum Number of Entries in Shared Memory No. of Entries in Shared Memory No. of Entries in Cache Memory Description Maximum number of entries permitted in the shared memory Total number of entries stored in the shared memory for the current calendar day Total number of entries stored in the cache memory for the current calendar day

Query Memory Consumption

You can display the memory consumption for each OLAP cache type at query level for the current day. This iView is tabular and provides the following information: Information Query No. of Access Description Technical name of the query cache object Number of times the query cache object for a particular data selection was read from the OLAP cache

Department of MCA

29

Cache Monitoring Tool No. of Bytes Hit Ratio

USN: 1MJ09MCA08 Size of the data selection (in KB) for the executed query cache object Ratio of number of bytes to the number of times the query cache object was read from the OLAP cache (number of bytes/number of times accessed).

Following are the several reasons why I prefer Spring Framework: 1. It addresses important areas that other popular frameworks don't. Spring focuses around providing a way to manage your business objects. 2. Spring is comprehensive and modular. Spring has a layered architecture, meaning that you can choose to use just about any part of it in isolation, yet its architecture is internally consistent. So you get maximum value from your learning curve. You might choose to use Spring only to simplify use of JDBC, for example, or you might choose to use Spring to manage all your business objects. And it's easy to introduce Spring incrementally into existing projects. 3. Spring is designed from the ground up to help you write code that's easy to test. Spring is an ideal framework for test driven projects. 4. Spring is an increasingly important integration technology, its role recognized by vendors large and small. 5. The Spring Framework is the core of the Spring Portfolio , an increasingly complete solution for enterprise Java development, exhibiting the same consistency of approach developed in the Spring Framework itself. Architectural benefits of Spring

Spring can effectively organize your middle tier objects. Spring takes care of plumbing that would be left up to you if you use only Struts or other frameworks geared to particular J2EE APIs. And Spring's configuration management services can be used in any architectural layer, in whatever runtime environment. Spring can eliminate the proliferation of Singletons seen on many projects. In my experience, this is a major problem, reducing testability and object orientation. Spring eliminates the need to use a variety of custom properties file formats, by handling configuration in a consistent way throughout applications and projects. Ever wondered what magic property keys or system properties a particular class looks for, and had to read the Javadoc or even source code? With Spring you simply look at the class's JavaBean properties or constructor arguments. The use of Inversion of Control and Dependency Injection (discussed below) helps achieve this simplification. Spring facilitates good programming practice by reducing the cost of programming to interfaces, rather than classes, almost to zero. Spring is designed so that applications built with it depend on as few of its APIs as possible. Most business objects in Spring applications have no dependency on Spring. Applications built using Spring are very easy to test. For certain unit testing scenarios, the Spring Framework provides mock objects and testing support classes. Spring also provides unique integration testing functionality in the form of the Spring TestContext Framework and legacy JUnit 3.8 support classes that enable you to test your code quickly and easily, even while accessing a staging database.

Department of MCA

30

Cache Monitoring Tool

USN: 1MJ09MCA08

Spring helps you solve problems with the most lightweight possible infrastructure. Spring provides an alternative to EJB that's appropriate for many applications. For example, Spring can use AOP to deliver declarative transaction management without using an EJB container; even without a JTA implementation, if you only need to work with a single database, or want to avoid two phase commit. Spring provides a consistent framework for data access, whether using JDBC or an O/R mapping product such as TopLink, Hibernate or a JPA or JDO implementation. Spring provides a consistent, simple programming model in many areas, making it ideal architectural "glue." You can see this consistency in the Spring approach to JDBC, JMS, JavaMail, JNDI and many other important APIs

Department of MCA

31

Das könnte Ihnen auch gefallen