Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

An ultra-lightweight high-precision logger for OpenJDK

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

    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

    • What GPU kernels mean for your distributed inference

    • Debugging image mode with Red Hat OpenShift 4.20: A practical guide

    • EvalHub: Because "looks good to me" isn't a benchmark

    • SQL Server HA on RHEL: Meet Pacemaker HA Agent v2 (tech preview)

    • Deploy with confidence: Continuous integration and continuous delivery for agentic AI

    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
    © 2026 Red Hat

    Red Hat legal and privacy links

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

    Chat Support

    Please log in with your Red Hat account to access chat support.