Accessing JDBC Data Source metrics from an application on a Weblogic Server

I recently felt the need for accessing the metrics / statistics of a JDBC Data Source from within an application that is deployed on a Oracle Weblogic Server. I did not succeed right away, so I document it here.

Basically we just need some calls to JMX. Using the Weblogic RuntimeServiceMBean we navigate from ServerRuntime and JDBCServiceRuntime to JDBCDataSourceRuntimeMBeans. From there we get ObjectNames for each JDBC Data Source that we can access from our application. Using these object names we can retreive the metrics.

First we get the MBeanServer via JNDI:

  1. MBeanServer getMBeanServer() throws NamingException {
  2.   InitialContext ctx = new InitialContext();
  3.   MBeanServer server = (MBeanServer) ctx.lookup("java:comp/env/jmx/runtime");
  4.   return server;
  5. }

Then we navigate as described before:

  1. ObjectName[] getJdbcDataSourceRuntimeMBeans(MBeanServer server)
  2.       throws MalformedObjectNameException, AttributeNotFoundException, MBeanException,
  3.       InstanceNotFoundException, ReflectionException {
  4.     ObjectName service = new ObjectName(
  5. "com.bea:Name=RuntimeService,");
  6.     ObjectName serverRT = (ObjectName) server.getAttribute(service, "ServerRuntime");
  7.     ObjectName jdbcRT = (ObjectName) server.getAttribute(serverRT, "JDBCServiceRuntime");
  8.     ObjectName[] dsRTs = (ObjectName[]) server.getAttribute(jdbcRT, "JDBCDataSourceRuntimeMBeans");
  9.     return dsRTs;
  10.   }

To get the current number of active connections and the current capacity of the connection pool, we access the attributes ActiveConnectionsCurrentCount and CurrCapacity:

  1. MBeanServer server = getMBeanServer();
  2.       ObjectName[] dsRTs = getJdbcDataSourceRuntimeMBeans(server);
  3.       for (ObjectName dsRT : dsRTs) {
  4.         String name = (String) server.getAttribute(dsRT, "Name");
  5.         Integer activeConnectionsCurrentCount =
  6.             (Integer) server.getAttribute(dsRT, "ActiveConnectionsCurrentCount");
  7.         Integer currCapacity =
  8.             (Integer) server.getAttribute(dsRT, "CurrCapacity");
  9.     // do something with these metrics
  10.       }

There are a bunch of metrics. Here is a list. You can enumerate them using MBeanAttrbuteInfo:

  1. /**
  2.    * Returns MBean-Attribute Infos such as Name, Type and Description
  3.    */
  4.   public MBeanAttributeInfo[] getMetricsAttributeInfos() {
  5.     try {
  6.       MBeanServer server = getMBeanServer();
  7.       ObjectName[] dsRTs = getJdbcDataSourceRuntimeMBeans(server);
  8.       if (dsRTs.length>0) {
  9.         return server.getMBeanInfo(dsRTs[0]).getAttributes();
  10.       }
  11.     } catch (Exception e) {
  12.       // your favourite error logging mechanism here...
  13.     }
  14.     return new MBeanAttributeInfo[]{};
  16.   }

every MBeanAttributeInfo contains name, type and description of the attribute.

Note: I am using Weblogic Server 11g here. I have not tried this on WLS 12c.

JavaMail ignores timeout from POP3 server

At work our application reads email from a number of POP3 servers using JavaMail. If you trigger the POP3 server’s timeout the session is closed silently und JavaMail does not complain on session.close. In the result, the message is not deleted and will be processed again on the next turn of the background processing task. To fix this, you need to check the state of the POP3 folder after processing each message. Read on for more details on this issue.


Some of the mails our application is getting are not only “messages” meant to be read by humans but contain structured information that is processed. This means DB operations. Processing takes not more than a few seconds – unless the Oracle DB optimizer chooses to take a bad SQL execution plan. At least this is what happened to us last week: the processing of a structured message took like 20 minutes.

The symptom then was that after the application was finished processing the email, it did not deleted the message from the server. It then started processing the mail in the next turn. As we found out the POP3 server (qpopper) has configured a timeout of five minutes. After that it answers with an “-ERR” status code to the next client command. The code we used to process the mail was roughly this:

  1. try {
  2.   mail = pop3Folder.getMessage(mailIndex + 1);
  3.   // ... do something with mail ...
  4. } finally {
  5.   mail.setFlag(Flags.Flag.DELETED, true);
  6. }
  7. folder.close();

When setting the delete flag, JavaMail sends the DELE command. That was answered with “-ERR” (from POP3 protocol exchange):

S: +OK 1 1866
S: ...
S: -ERR POP timeout from
S: +OK Pop server at signing off.

and the session is gone. Using session.close did not complain. So no exception occured. In fact, if an exception had occured we already had an compensation mechanism that would have prevented processing the same mail again. Also it would have pointed us to the problem more directly.


The solution is to check the protocol state using folder.isOpen after processing a mail.

If that folder is not open, the mails you have so far processed have not been deleted because in POP3, mails are deleted when closing a folder. So open the folder again and delete all messages (messageRead) that you have processed before. Then carry on, i.e. close the folder.

  1. boolean isOpen = folder.isOpen();
  2. if (!isOpen) {
  4.   final int mailCount = folder.getMessageCount();
  5.   for(int i = 1; i <= Math.min(messageRead, mailCount); i++) {
  6.     Message mail = folder.getMessage(i);
  7.     mail.setFlag(Flags.Flag.DELETED, true);
  8.   }
  9. }
  10. // folder.close in "normal" code flow

The folder.isOpen sends a NOOP command and evaluates the response, so the “-ERR” server code is not gone unnoticed.

Doing it right

POP3 was designed to download mails rather quickly. A better solution is to fetch emails from POP3, store it somewhere and only then process them (“offline”).

Default timeouts for network connections in Java

You often find the answer to “How do I set default timeouts for (outgoing) network connectins in Java” is

  1. System.setProperty("", "30000");
  2. System.setProperty("", "30000");

But this may or may not work. Because, as stated by Sun in 2005:

Yes, it [the default timeout] is cached, or more precisely it is looked up only at startup time. This is by design.

Playing around with the code in the bug database entry linked to above and netcat, I found that it is also true for Java 6. Chances are high that it is true for Java 7, too.

What is meant by “startup time” is using some network connection, e.g. HttpURLConnection. That means if there has some network connection been used before the properties are programmatically set, no network connections will use these timeout values!! If you set these properties in the JEE ContextListener or some startup-servlet they may have no impact anymore because your web container may already have used a network connection. Better use the commandline to pass these parameters.

Berlin Expert Days 2012

Die “Berlin Expert Days 2012” war eine zweitägige Softwareentwicklungs-Konferenz in Berlin. Ich war das erste Mal dabei und es hat mir gut gefallen. Die Konferenz findet im Fachbereich Informatik an der FU-Berlin statt. Sie ist nicht sehr groß (Räumlichkeiten: 1 Hörsaal, 2 Seminarräume), wobei dieses Jahr wohl nicht alle Anmeldungen auch ein Ticket bekommen haben. Den Preis von unter 100 EUR finde ich sehr moderat.

Die meisten Talks, die ich gehört habe, waren interessant und gut präsentiert. Ausnahmen bestätigten die Regel. Ich schreibe mal einzelne Posts zu den Talks.

Ich habe sogar einen Ex-Kommolitonen wieder getroffen.

Weblogic does not stop in Eclipse


While using Oracle Enterprise Pack for Eclipse (Version with Weblogic 11gR1 (that is for some weeks
I suddenly was not able to stop the Weblogic server. Whatever method I used to stop the server, it didn’t work. When I restarted Eclipse
the Weblogic server started automatically again. Also, there were no more console output neither from the server nor from my application.


I manually started the “bin\stopWeblogic.cmd” skript in the domain home directory using the Windows console. You can go to the
domain home by right-clicking the server in the “Servers” view and choosing “Go To > Domain Home”. When I started the server
again from within Eclipse, the console output was there again and stopping the server worked well again. All is well :-)

Einfache Konstruktoren

Gespräch mit Kollege:
Gegeben Klasse A und Klasse B extends A und ich rufe im Konstruktor von A eine Methode auf, die in B überschrieben wird und die dort auf eine in B definierte Variable zugreift, dann ist diese Variable zum Zeitpunkt des Aufrufs nicht initialisiert. Das stimmt.

Wozu brauchst Du das?
Klasse Gruppenbaum, im Konstruktor lese ich Baum aus DB.
Na das ist ja nicht so gut. Konstruktoren sollten ihr Objekt in einen definierten Zustand bringen, mehr aber auch nicht. Wurde schon vor langer Zeit beschrieben.

Finalizer in Java: lieber Finger weg!

Laut Java-Spezifikation werden Finalizer in Java aufgerufen, bevor das entsprechende Objekt durch den Garbage Collector aus dem Speicher entfernt wird. Das klingt erst mal verlockend – hier könnte man ja automatische das Freigeben von Resourcen unterbringen.

Aber! Es wird nicht garantiert, wann der Finalizer aufgerufen wird. Die freizugebenden Resourcen sind solange blockiert. Schlimmer kommt es noch, wenn ein Finalizer ungewöhnlich lange für die Verarbeitung benötigt. Dann können die Resourcen, die die Objekte der anderen anstehenden Finalizer halten, nicht freigegeben werden. Dies kann zu Out-of-Filehandles oder zu Out-of-Memory-Fehlern führen, wenn die Entwickler sich auf die zeitnahe Abarbeitung von Finalizern verlassen.

Dies ist uns letztens passiert: Unsere Anwendung beendet sich nachweisbar nach einigen hundert Webservice-Aufrufen. Ergebnis der Problemanalyse: Ein Objekt einer Klasse des Oracle IAS scheint den Finalizer-Warteschlange zu blockieren, somit werden Objekte aus dem AXIS-(1.0)-Framework nicht finalisiert, die jedoch Referenzen auf speicherfressende DOM-Objektbäume halten. Diese DOM-Objektbäume können dadurch nicht garbage-collected werden, sammeln sich an und schliesslich kommt der Out-of-Memory-Fehler. Im generierten Webservice-Stub-Code haben wir manuell den Aufruf an den Finalizer (genauer: an die dispose-Methode) eingefügt und siehe da, dass Problem ist beseitigt.

An einer anderen Stelle (ebenfalls AXIS) sind wir vor 1-2 Jahren in ein ähnliches Problem gelaufen, da ging es jedoch um FileHandles oder Netzwerk-Ports. Auch da half manuelles freigeben der Resourcen.

Fazit: Es ist besser, die Resourcen von Hand freizugeben. “Zur Sicherheit” mag man noch einen Finalizer schreiben, aber wenn dieser wiederum die Finalize-Warteschlange blockieren könnte (etwa weil auf ein Netzwerk-Timeout gewartet wird), dann sollte man auch davon die Finger lassen.

Tools zum Analysieren von Memory-Dumps: