Monday, June 15, 2020

Steps and tips to improve performance and avoid memory leaks of a java Application


In general while developing any java application, we might anticipate some bugs,errors and memory leaks in common which will impact the performance of the application and effect the maintainability. All these issues may occur due to gaps in the requirements ,improper resource utilization, improper usage of design patterns or not usage of required essential design patterns, due to network overheads, non-addressable of pestilential memory leakages and improper usage of collections etc.  

We will try to discuss and address the above mentioned issues that are caused for the poor performance of the Application and discuss how we can improve the performance of the application in a better way with the possible solutions, potentially that we can implement where ever they are required.

Optimize your I/O operations: Java applications that utilize Input/Output are  excellent candidates for performance tuning. Profiling of java applications that handle significant valumes of data will show significant of time spent in I/O operations. This means substantial gains can be had from I/O performance tuning. Therefore I/O efficiency should be a high priority for developers looking to optimally increase performance.

The basic rules for speeding up I/O performance are :

  • Minimize accessing the hard disk.
  • Minimize accessing the underlying operating system.
  • Minimize processing bytes and characters individually.

Use buffering when writing to and reading from files and /or streams to improve java I/O performance. Avoid writers/readers if you are dealing with only ASCII characters. You can use streams instead, which are faster. Avoid premature flushing of buffers. 

Eg: FileReader fileReader = new FileReader(file);
      BufferedReader br = new BufferedReader(fileReader);
      While(br.readeLine() != null) 
        count++

Also make use of the performance and scalability enhancing features such as non-blocking and asynchronous I/O , mapping of file to memory etc offered by the NIO ( new I/O).




Pool Valuable System Resources: Pool valuable system resources like  threads,database connections,socket connections etc. Emphasize on a reuse of threads from a fool of threads. Creating new threads and discarding them after use can adversely affect the performance. Also consider consider using multi-threading in your single-threaded applications where possible to enhance the performance.

Eg: Sample Thread:


Creating Sample Thread Pool:



Out Put:


Optimize the pool sizes based on system and application specifications.

Properly close all the database connections and socket connections 

Usually object pooling is handled by a Java EE application server. If you need to do it yourself, best to use something like Apache's object pool. Don't write one yourself, thread safety and other issues can make it complicated.

Minimize network overheads: Minimize network overheads by retrieving several related items simultaneously in one remote invocation if possible. Remote method invocations involve a network round-trip, marshalling and unmarshalling  of parameters, which can cause huge performance problems if the remote interface is poorly designed.

 Hence take proper precautions while making any network calls , marshalling and unmarshalling in your applications and design the application properly to handle the unavoidable network calls.


  • Minimize the use of the casting or runtime type checking like instanceof in frequently executed methods or in loops.The casting and instanceof checks for a class marked as final will be faster. Using instanceof construct  is not only ugly but also unmaintainable .To overcome this issue better use visitor pattern in the application.

  • Do not compute  constants inside a large loop. Better compute them outside the loop and have call to the same. 

  • Minimize JNI calls in your code.

  • Minimize calls to Date,Calendar etc related classes.

  • Better avoid using System.out.println(); and use logging frameworks like Log4j or Apache commons logging etc , which uses I/O buffers.Frameworks like Log4j are configurable , flexible,extensible and easy to use.

  • Exception creation can be expensive because it has to create the full stack trace. The stack trace is obviously useful if you are planning to log or display the exception to the user. But if you are using your exception to just control the flow, which is not recommended, then throw an exception, which is pre-created. An efficient way to do this is to declare a public static final Exception in your Exception class itself.
Manage your object to avoid potential memory problems or leaks: Remove references to the short-lived objects from long-lived objects like java  collections etc to minimize any potential memory leaks.Also reuse objects where ever possible. It is cheaper to recycle objects rather than creating a new object each time.

  • Avoid creating extra objects unnecessarily .For example use mutable StringBuffer/StringBuilder classes instead of immutable String class objects in computation expensive loops.

  • Automatic garbage collection is one of the most highly touted conveniences of java. However, it comes at a price. Creating and destroying objects occupies a significant chunk of the JVMs time. Wherever possible, you should look for ways to minimize the number of objects created in your code.

  • If repeated code within a loop, avoid creating new object for each iteration. Create objects before entering the loop (i.e. outside the loop) and re use them if possible.

  • For complex objects that are used frequently, consider creating a pool of recyclable objects rather than always instantiating new objects. This adds additional burden on the programmer to manage the pool, but in select cases can represent an order of magnitude performance again.

  • Use lazy initialization when you want to distribute the load of creating large amounts of objects. Use lazy initialization only when there is merit in the design.
  • Where applicable catching can be used to improve performance by reading in all the lines of a file into a java collection class like an ArrayList or HashMap and subsequently access the data from an in-memory collection instead of the disk.





No comments:

Post a Comment

Hello Buddy, if you have any doubts or need any clarification , feel free to comment. Thanks.