Skip to main content
Redhat Developers  Logo
  • Products

    Platforms

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat AI
      Red Hat AI
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • View All Red Hat Products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat Developer Hub
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat OpenShift Local
    • Red Hat Developer Sandbox

      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Secure Development & Architectures

      • Security
      • Secure coding
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • Product Documentation
    • API Catalog
    • Legacy Documentation
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

An ultra-lightweight high-precision logger for OpenJDK

June 24, 2014
Andrew Haley
Related topics:
Java
Related products:
Red Hat build of OpenJDK

Share:

    I had an interesting question from one of our developers here at Red Hat:

    "When I was investigating a performance issue in our project after switched to oracle's jdk7u40, I found a performance regression in class sun.net.www.protocl.http.HttpURLConnection.getOutputStream(). This method takes more cpu time than with jdk7u25."

    And it does, much more time. In fact, when fixedLengthStreamingMode is enabled HttpURLConnection.getOutputStream() takes ten times as long: about 1.2 milliseconds versus 47 microseconds.

    So, I traced through getOutputStream() deep into the class library, but it's hard to tell exactly how long a chunk of Java code takes to execute. I wanted to be able to add log points so that I could measure intervals between points in the code. Ideally, the interface would be something like

       logEvent(int n, String s)
    

    where n is some sort of counter, s is recorded in the log, and when the program ended the log would be printed to a file somewhere. I didn't want to modify the test program any more than entirely necessary, just to insert log points into the Java library around whatever I wanted timing.

    It is possible to write this in pure Java, but there is a problem: the logging itself takes quite a long time. Creating a log item like this

        static class LogItem {
            public int n;
            public String s;
            public long time;
    
            LogItem(int n, String s) {
                this.n = n; this.s = s;
                this.time = System.nanoTime();
            }
        }
    

    takes more than 600 nanoseconds, mostly because of the call to System.nanoTime(). This is much too intrusive. What I wanted was a flyweight logger that can be called from anywhere and affects running programs as little as possible.

    This is where one of the great advantages of Free and Open Source software comes into play. Freedom 1 in the Free Software Definition is the ability to study how a program works, and change it so it does your computing as you wish. So, how hard would it be to add a very high-precision low-overhead logger to OpenJDK?

    Intel Core i7 processors have the RDTSCP instruction, which is a very high-precision timer. It has a few disadvantages, particularly on multi-socket computers where the TSC isn't synchronized, but for measuring very short intervals of time it can't be beat. TSC ticks at some fixed frequency; on my box it's 3.2 GHz. So, to get time in nanoseconds you divide by 3.2.

    Using GCC you read the TSC like this:

    static __inline__ unsigned long long rdtsc(void)
    {
      unsigned hi, lo;
      __asm__ __volatile__ ("rdtscp" : "=a"(lo), "=d"(hi));
      return ( (unsigned long long)lo)|( ((unsigned long long)hi) <<32 );
    }

    And this is everything I need for a flyweight logger.

    This is the log itself. It's a fixed-size array of log records, statically allocated in libjava.so. The idea here is that the actual act of logging won't have to allocate any dynamic memory.

    typedef struct {
      unsigned long time;
      int n;
      char str[64];
    } log_item;
    
    #define LOG_SIZE 1048576
    
    static log_item a_log[LOG_SIZE];
    static unsigned int log_counter = ~0;
    

    I added my logging method to sun.misc.Unsafe, just for convenience:

    static void atexit_fn(void);
    
    /*
     * Class:     sun_misc_Unsafe
     * Method:    logEvent
     * Signature: (ILjava/lang/String;)V
     */
    JNIEXPORT void JNICALL Java_sun_misc_Unsafe_logEvent
      (JNIEnv *env, jclass cla, jint n, jstring s)
    {
      (void)cla;
      if (log_counter == ~0) {
        atexit(atexit_fn);
        log_counter = 0;
      }
      a_log[log_counter].n = n;
      if (s) {
        jsize len = (*env)->GetStringLength(env, s);
        if (len >= 64) len = 63;
        const jchar *carray = (*env)->GetStringCritical(env, s, NULL);
        char *dst = a_log[log_counter].str;
        const jchar *src = carray;
        while (len--)
          *dst++ = *src++;
        *dst = 0;
        (*env)->ReleaseStringCritical(env, s, carray);
      } else {
        a_log[log_counter].str[0] = 0;
      }
      a_log[log_counter].time = rdtsc();
      log_counter++;
      log_counter %= LOG_SIZE;
    }
    

    So, the very first time that Unsafe.logEvent() is called, we register an atexit callback function. Then we log the event and its time and (optionally) a string that's passed to the logger. If we overrun our log, we just wrap round. There's no real thread safety: two threads might overwrite the same log entry. This log routine does not do anything that isn't necessary. Also, nothing in the call to Unsafe.logEvent() allocates any memory.

    Here's the callback which prints the log when Java exits:

    static unsigned long adjust(unsigned long dt) {
      return dt * 10 / 32;   // Convert 3.2GHz ticks to ns
    }
    
    static void atexit_fn(void) {
      jlong time0;
      jlong last;
      FILE *outf = fopen("/tmp/deleteme", "w+");
      if (! outf) perror("fopen");
      int i;
      for (i = 0; i < log_counter; i++) {
         log_item *item = &a_log[i];
         if (item->n == 0)
          time0 = item->time;
        fprintf(outf, "%ld (%ld): %d %sn", adjust(item->time - time0),
    	    adjust(item->time - last),
    	    item->n, item->str);
        last = item->time;
      }
    }
    

    So, how long does a log event actually take to execute? We can measure it:

            for (int i = 0; i < 1000000; i++) {
            	sun.misc.Unsafe.logEvent(0, null);
            	sun.misc.Unsafe.logEvent(1, null);
            	sun.misc.Unsafe.logEvent(2, null);
            }
    

    And the log:

    0 (27): 0
    28 (28): 1
    56 (27): 2
    0 (28): 0
    ...
    

    Oh my goodness that's fast. 28 nanoseconds. 20 times faster than a call to System.nanoTime(). 28 nanoseconds is the time it takes for a photon of light to pass from one end of a London bus to the other.

    What happens if we pass a string to Unsafe.logEvent() ?

            for (int i = 0; i < 1000000; i++) {
            	sun.misc.Unsafe.logEvent(20, null);
            	sun.misc.Unsafe.logEvent(25, "One two three four");
            	sun.misc.Unsafe.logEvent(30, null);
    
    0 (21): 0
    75 (75): 25 One two three four
    103 (27): 30
    

    Hmmm, that's slower: 75 nanoseconds. If you're trying to measure a very small interval that's a problem, but sometimes you need a little bit more information than an integer. It would have been possible to convert this native method call into a HotSpot intrinsic for even lower overhead, but the overhead is already so low that I didn't bother.

    With this tool, all that you need to do to measure an interval in the OpenJDK class library (or indeed any Java code) is insert a pair of Unsafe.logEvent() calls around it. There is some small timing effect, but it's really not very much.

    The full patch (for OpenJDK 7) is here

    Would it have been better if OpenJDK had a lightweight logging facility like this built in? I'm not sure. Maybe, maybe not.  It would have to be much more general-purpose, would inevitably have more bells and whistles, and would be more complex. You don't get flyweight anything from generality. Maybe this is one of those cases where a quick hack is just what you want.

    This is why Freedom #1 is so vital: without the ability to read the source code for OpenJDK and change it, this task would have been far harder.

    Last updated: April 25, 2022

    Recent Posts

    • DeepSeek-V3.2-Exp on vLLM, Day 0: Sparse Attention for long-context inference, ready for experimentation today with Red Hat AI

    • How to deploy the Offline Knowledge Portal on OpenShift

    • Autoscaling vLLM with OpenShift AI

    • Filtering packets from anywhere in the networking stack

    • PostGIS: A powerful geospatial extension for PostgreSQL

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2025 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue