Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Groovy Quick Start


[ 26 ]

We already know that Groovy is a language built on top of the JVM and that it runs
as Java bytecode. So, how is it possible for a Groovy script to run without being
compiled to a Java class? The answer is that the Groovy scripting engine compiles
scripts on the fly and loads the bytecode onto the JVM. We will find out how to
compile our Groovy script later in the chapter.


The important thing to note for now is that even though our scripts seem to be
running on the command line, they are in fact running on a JVM, and as a result, we
have access to all of the power of the JVM and Java APIs. To demonstrate, let's look
at a more complicated script.


The Java management extension JMX is an extremely useful component of the Java
platform. JMX is a framework for managing and monitoring applications, system
objects, and devices. In JMX, resources are represented as MBeans and we can use
the JMX APIs to access the resources to monitor the state of our application.


Typical JMX clients such as jManage tend to be heavy-weight GUI applications that
allow application resources to be inspected. Sometimes, I just want to monitor one or
two values that are relevant to the performance of my application, such as its current
heap usage, and log it to a file at intervals.


Consider the following Groovy script, monitor.groovy, which connects to the
platform MBean of a remote JVM and monitors its heap usage before and after a
garbage collection operation:


import java.lang.management.*
import java.lang.management.ManagementFactory as Factory
import javax.management.remote.JMXConnectorFactory as JMX
import javax.management.remote.JMXServiceURL as ServiceURL

def serverUrl = 'service:jmx:rmi:///jndi/rmi://localhost:3333/jmxrmi'
def server = JMX.connect(
new ServiceURL(serverUrl)).MBeanServerConnection

println "HEAP USAGE"
def mem = Factory.newPlatformMXBeanProxy(server,
Factory.MEMORY_MXBEAN_NAME, MemoryMXBean.class)
def heapUsage = mem.heapMemoryUsage
println """Memory usage : $heapUsage.used"""
mem.gc()
heapUsage = mem.heapMemoryUsage
println """Memory usage after GC: $heapUsage.used"""

http://www.ebook3000.com
Free download pdf