by BehindJava

The Performance Impact of java.lang.System.getProperty()

Home » java » The Performance Impact of java.lang.System.getProperty()

In this tutorial we are going to see about avoiding blocked threads.

‘java.lang.System.getProperty()’ is a common API used by Java developers to read the System properties that are configured during application startup time. i.e. when you pass “-DappName=userService” as your application’s startup JVM argument, the value of the ‘appName’ system property can be read by invoking the ‘java.lang.System.getProperty()’.

Example:

public static String getAppName() {    
  
    String app = System.getProperty("appName");   
    return app;
}

When the above method is invoked, ‘userService’ will be returned. However, if ‘java.lang.System.getProperty()’ is used in a critical code path, it has the potential to degrade the application’s performance.

What Is the Performance Impact of Using ‘java.lang.System.getProperty()’ API?

  • ‘java.lang.System.getProperty()’ API underlyingly uses ‘java.util.Hashtable.get()’ API.
  • ‘java.util.Hashtable.get()’ is a synchronized API. It means only one thread can invoke the ‘java.util.Hashtable.get()’ method at any given time. If a new thread tries to invoke ‘java.util.Hashtable.
  • get()’ API when the first thread is still executing it, the new thread will be put in a BLOCKED state. When a thread is in the BLOCKED state, it won’t be able to progress forward. Only when the first thread completes executing the ‘java.util.Hashtable.get()’ API, a new thread will be able to progress forward.
  • Thus if ‘java.lang.System.getProperty()’ or ‘java.util.Hashtable.get()’ is invoked in critical code paths, it will impact the response time of the transaction.

What is the Solution?

Here are the potential solutions to address this problem:

  1. Upgrade to JDK 11: Starting from JDK 11, Synchronized ‘HashTable’ has been replaced with ‘ConcurrentHashMap’ in java.util.Properties. Thus when you upgrade to JDK11, you will not run into this problem.
  2. Caching the values: In a significant number of applications, System properties don’t change during runtime. In such circumstances, we don’t have to keep invoking ‘java.lang.System.getProperty()’ API on every single transaction. Rather, we can invoke ‘java.lang.System.getProperty()’ API once, cache its value, and return the cached value on all future calls, as shown in the below code snippet.
private static String app = System.getProperty("appName");  

public static String getAppName() {    
    return app;
}

In the above code, ‘’java.lang.System.getProperty()’ is now assigned to a static member variable. It means this API will be called during application startup time, that too only once. From that point, if anyone invokes the getAppName() API, he will be returned the cached value. Thus, application threads will not be put into the BLOCKED state at runtime. This simple change can improve the application’s overall response time.