Skip to content
Tutorials Center
My learning

Topics

Lesson 98 of 119 ยท Architecture and Deployment

JNDI and JMX Management

Learn JNDI naming lookups and DataSource resources, then JMX MBeans, MXBeans, notifications and remote monitoring with JConsole, plus Spring, Actuator and security tips.

Two standards built into the JDK explain a lot of what application servers do behind your back. JNDI (Java Naming and Directory Interface) is how an application finds resources by name: the DataSource it should use, a mail session, an EJB, an LDAP entry. JMX (Java Management Extensions) is how a running JVM and the code inside it expose attributes and operations for monitoring and management: heap usage, thread counts, pool sizes, a switch to flush a cache. Tools like JConsole, VisualVM and Prometheus exporters rely on it.

Unlike the Jakarta EE libraries elsewhere in this course, both APIs live in the JDK (javax.naming and javax.management), so every example here runs for real on the code runner. In this lesson you will learn how a name lookup works and why servers configure resources that way, what an MBean is and how to write and register your own, how remote tools connect, and which security rules matter for both.

JNDI: finding things by name

A naming service maps names to objects, like a phone book. JNDI is the standard Java API in front of many such services: an application server's resource tree, an RMI registry, an LDAP directory, DNS. The core types are small:

Type Role
Context a set of name-to-object bindings: lookup, bind, rebind, unbind, list, createSubcontext
InitialContext the starting point; it uses the provider named in the environment to create the real context
NamingException the checked exception for everything: NameNotFoundException, NameAlreadyBoundException, NoInitialContextException

Inside an application server the environment is already configured, so you just write new InitialContext(). A standalone program has no provider unless you set java.naming.factory.initial (and a URL) in the environment or a jndi.properties file. The conventional namespaces of Jakarta EE are java:comp/env (the current component's environment), java:module, java:app and java:global. A servlet looks up its database like this:

Java
import javax.naming.*;
import javax.sql.DataSource;

DataSource ds;
try {
    Context ctx = new InitialContext();
    ds = (DataSource) ctx.lookup("java:comp/env/jdbc/shop");
} catch (NamingException e) {
    throw new IllegalStateException("DataSource not configured", e);
}
try (var connection = ds.getConnection()) { ... }

Notice what the code does not contain: a JDBC URL, a driver class, or a password. The administrator defines the resource in the server, for example in Tomcat's context.xml:

XML
<Context>
  <Resource name="jdbc/shop" auth="Container" type="javax.sql.DataSource"
            driverClassName="org.postgresql.Driver"
            url="jdbc:postgresql://db.internal:5432/shop"
            username="shop" password="${DB_PASSWORD}"
            maxTotal="20" maxIdle="5" />
</Context>

and the same WAR works in development, test and production with different databases and pool sizes. That is the point of JNDI: configuration outside the code, plus a connection pool shared and managed by the server (see connection pooling). In annotation style, a container injects the same object for you:

Java
@Resource(lookup = "java:comp/env/jdbc/shop")
private DataSource dataSource;

Spring can use a JNDI DataSource through spring.datasource.jndi-name=java:comp/env/jdbc/shop in Boot (see Spring Boot configuration), though most modern Boot applications configure their pool in application.yml instead and skip JNDI entirely.

Because InitialContext needs a provider, this runnable example registers a small in-memory one, the way a server's naming tree behaves. A dynamic proxy implements the few Context methods we use, and the DataSource is H2's real implementation. The application code in step 3 is exactly what you would write in a servlet:

Java A JNDI lookup of a DataSource

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The application sees only the DataSource interface and a name. The rebind step shows why operations teams like this: they can repoint jdbc/shop to a replica without touching the program. The other classic failures are the three exceptions at the end: NoInitialContextException (no provider configured, typical when you run server-code in a plain main or a unit test), NameNotFoundException (a typo, or the resource is not defined in this environment) and NameAlreadyBoundException (use rebind to replace).

Other JNDI providers and a warning

JNDI also has providers for LDAP (com.sun.jndi.ldap.LdapCtxFactory, used to search company directories and authenticate users), the RMI registry, and DNS. LDAP support makes JNDI powerful and dangerous: if an application ever calls lookup with a name that an attacker can influence, the attacker may point it at their own LDAP or RMI server and have it return an object that makes your JVM load remote code. That is the mechanism behind Log4Shell (CVE-2021-44228), where the logging library resolved ${jndi:ldap://...} inside log messages. Modern JDKs block the worst variants by default (com.sun.jndi.ldap.object.trustURLCodebase is false), but the rules remain:

  • Never pass user-controlled strings to Context.lookup, InitialContext.doLookup or anything that ends up there.
  • Keep libraries and the JDK patched, and prefer the java: namespaces you control.
  • Restrict outbound network access from application servers, and avoid enabling remote class loading.

JMX: managing a running JVM

JMX defines MBeans, managed beans: objects that publish attributes (readable and writable values), operations (methods) and notifications (events) in a uniform way. MBeans are registered in an MBeanServer under a unique ObjectName with the form domain:key=value,key=value, for example java.lang:type=Memory or com.example.shop:type=Cache,name=ProductCache. The JVM runs a platform MBeanServer and already registers MBeans for memory, threads, garbage collection, class loading, the operating system and the runtime. Frameworks add their own: Tomcat's request statistics, HikariCP's pool metrics (registerMbeans), Hibernate statistics, Kafka clients.

There are several kinds of MBean:

Kind How it is defined
Standard MBean a class Foo implementing an interface named FooMBean; getters and setters become attributes, other methods operations
MXBean an interface ending in MXBean; complex types are converted to open types (CompositeData) so any client can read them without your classes
Dynamic / Model MBean describes itself at runtime; used by generic frameworks

Attribute names come from the getter names: getHits() is the attribute Hits. A getter without a setter is read-only.

Writing and registering an MBean

The next program defines a standard MBean for a cache, registers it, and then behaves like JConsole: it starts a JMX connector on the loopback address, connects as a remote client, lists the attributes, listens for a notification, changes a setting and invokes an operation. It also lists some of the JVM's own MBeans:

Java Your own MBean, managed through a remote JMX connector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Several JMX ideas show up in that output:

  • Introspection. The client learns the attributes and operations from MBeanInfo, with no compiled dependency on CacheStats. That is how a generic console can show any application's beans.
  • Read-write attributes (MaxEntries) become editable fields in the console. Be careful which settings you make writable, because anyone with JMX access can change them.
  • Notifications. NotificationBroadcasterSupport lets the bean publish events, here an AttributeChangeNotification. Listeners are called asynchronously.
  • Operations (reset) become buttons in a tool. Keep them safe and idempotent.

The ObjectName follows a convention: a reversed-domain domain, a type key, and name for instances. queryNames accepts patterns such as java.lang:type=* or com.example.shop:*, so you can find all your beans in one call.

Built-in JVM MBeans worth knowing

Java
import java.lang.management.*;

MemoryMXBean memory = ManagementFactory.getMemoryMXBean();
System.out.println(memory.getHeapMemoryUsage());                   // used, committed, max

ThreadMXBean threads = ManagementFactory.getThreadMXBean();
long[] deadlocked = threads.findDeadlockedThreads();               // null if there is no deadlock

for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
    System.out.println(gc.getName() + ": " + gc.getCollectionCount() + " collections, " + gc.getCollectionTime() + " ms");
}

These are the numbers behind the JVM metrics that Actuator and Micrometer publish, and behind the tools in debugging and profiling.

Monitoring a running application

For a quick look at your own machine, run jconsole (or VisualVM) from the JDK and pick a local process: no setup is needed. To monitor a remote server, start the JVM with remote JMX enabled. These flags are real and should be used with authentication and TLS in production:

Terminal
java -Dcom.sun.management.jmxremote.port=9010 \
     -Dcom.sun.management.jmxremote.rmi.port=9010 \
     -Dcom.sun.management.jmxremote.authenticate=true \
     -Dcom.sun.management.jmxremote.password.file=/etc/app/jmxremote.password \
     -Dcom.sun.management.jmxremote.access.file=/etc/app/jmxremote.access \
     -Dcom.sun.management.jmxremote.ssl=true \
     -Djava.rmi.server.hostname=app.internal.example.com \
     -jar app.jar

Containers add a wrinkle: RMI embeds the host and port in its stubs, so you must publish the port and set java.rmi.server.hostname to an address the client can reach (the runnable example set it to 127.0.0.1, otherwise the connection tried a container-internal address and failed). A JMX port without authentication is a remote code execution hole, because an MBean client can load arbitrary MBeans. Expose it only on a private network or through an SSH tunnel.

JMX in Spring and Spring Boot

Spring can publish any bean as an MBean with annotations, so you rarely write the interface by hand:

Java
@Component
@ManagedResource(objectName = "com.example.shop:type=Cache,name=ProductCache")
public class ProductCache {

    @ManagedAttribute
    public int getSize() { return map.size(); }

    @ManagedAttribute
    public void setMaxEntries(int max) { this.max = max; }

    @ManagedOperation(description = "Remove all cached products")
    public void clear() { map.clear(); }
}

In Spring Boot, set spring.jmx.enabled=true to export these and expose Actuator endpoints over JMX. Today many teams move from JMX to Micrometer metrics scraped by Prometheus, because HTTP-based monitoring is easier to run across firewalls and clusters, but JMX remains the universal local diagnostic tool and the way many server products, Kafka and Cassandra among them, publish their internals.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main benefit of looking up a DataSource through JNDI?

    JNDI externalizes configuration. The administrator defines and manages the pooled resource, and the application only knows its name.
  2. 2. You call new InitialContext().lookup(...) in a plain main method and get NoInitialContextException. What is the likely cause?

    Outside a container there is no initial context factory. Configure one (jndi.properties or system properties) or use a test double.
  3. 3. Why was JNDI central to the Log4Shell vulnerability?

    Passing user-controlled strings to JNDI lookups lets an attacker point the JVM at their own LDAP or RMI server. Never feed untrusted input to lookup.
  4. 4. Which interface name makes a class a standard MBean named Cache?

    A standard MBean pairs a class with an interface named after it plus MBean. An MXBean uses the MXBean suffix instead.
  5. 5. Why is an open JMX port without authentication dangerous?

    Remote JMX gives full management power. Use authentication, TLS, a private network or an SSH tunnel.

Summary

  • JNDI maps names to objects. InitialContext needs a provider; servers expose resources under java:comp/env, so code looks up java:comp/env/jdbc/shop instead of hard-coding a database.
  • Typical errors are NoInitialContextException, NameNotFoundException and NameAlreadyBoundException. Never pass untrusted input to lookup (Log4Shell).
  • JMX exposes MBeans (attributes, operations, notifications) under ObjectNames in an MBeanServer; the JVM registers memory, thread, GC and runtime MBeans for you.
  • Standard MBeans use the FooMBean naming rule; MXBeans use open types for portable clients; connectors let JConsole and other tools manage a process remotely.
  • Secure remote JMX with authentication, TLS and network restrictions, and set java.rmi.server.hostname correctly in containers.
  • Spring's @ManagedResource and Actuator publish beans over JMX, while Micrometer and Prometheus cover cluster monitoring.

Next: Deploying Java to Kubernetes shows how to run these services in a cluster with proper probes, resource limits and configuration.