Friday, June 28, 2013

How to find unused jars in Java EE web application?

      I was exploring options on how to identify unused jar files in a web application packaged in war/ear file. One could argue that they are unused and why should I bother it as they don't get loaded by the classloader. In fact, it gives couple of advantages. By doing this, the war file size will be smaller that makes it faster to deploy. During deploy, the application server scans all the jar files for tag library definitions(tlds) and possibly other things. By removing unused ones, the startup time will get reduced (eventhough it is not noticeable) There are multiple ways to do it depending upon the frameworks/libraries that you use in your application.

Maven's dependency plugin
     Maven has a plugin to analyze the dependencies of your web application. It uses the project's pom.xml to identify the dependent jars (including transitive dependencies).
mvn dependency:analyze - go to your web project folder and run this command; This will list used and unused jars. One caveat is that this works only if your application does not rely on frameworks such as spring, guice. Otherwise the jars that maven classifies as unused might be used while the application is running.

Use java's -verbose:class option
This would be the best solution if your web application uses dynamic class loading and maven's dependency plugin does not help. The solution would be a multistep approach as described below:-
  1.  Add a new JVM parameter -verbose:class to your server. This would log the jar files from which each class is loaded.
  2. Deploy your web application and do a functional test (to capture the classes that are dynamically loaded).
  3. Grep the logs for individual jar files.
  4. If you are using maven, identify the group id and artifact id from the jar file name.
  5. Remove the jar files that are not listed in step 3.



1 comment: