Sunday, February 24, 2013

Servlet Monitoring with Metrics

Metrics from Coda Hale is a wonderful library to ease the monitoring of the performance of your code. It gives you tons of metrics directly via JMX, logs or CSV files.

I use it to monitor the performance of servlet in a JEE6 application. It is very simple to set up:
  1. Add the following dependency to your pom.xml:
  2. Declare a Timer:
         * the timer for monitoring incoming HTTP POST requests.
        private final Timer postTimer = Metrics.newTimer(getClass(), "post-requests-timer", TimeUnit.MILLISECONDS, TimeUnit.SECONDS);
    This code instantiates a new Timer where duration is measured in milliseconds and rate in seconds (to compute request per second).

  3. Use the previous Timer when handling HTTP request:
         * Handles the HTTP
         * POST method.
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            // starts stopwatch
            final TimerContext context = postTimer.time();
            // handles request and response, calls business logic
            // ends stopwatch
  4. Put some load on your servlet and monitor it using JConsole for instance:


  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.

  2. I think this is the best article today. Thanks for taking your own time to discuss this topic, I feel happy about that curiosity has increased to learn more about this topic. Keep sharing your information regularly for my future reference.
    Java Courses in chennai