Resolving ClassCastException (Same Class Name) Due to Lingering ClassLoader References During JAR Redeployment
search cancel

Resolving ClassCastException (Same Class Name) Due to Lingering ClassLoader References During JAR Redeployment

book

Article ID: 447153

calendar_today

Updated On:

Products

VMware Tanzu Data Suite

Issue/Introduction

During a JAR redeployment or upgrade, you may encounter an intermittent java.lang.ClassCastException where a class seemingly fails to cast to itself.

java.lang.ClassCastException: class <class name> cannot be cast to class <class name> is in unnamed module of loader xxxxxxx

Cause

This paradox (where Class A cannot be cast to Class A) occurs because classes from both the old and new deployments are being referenced simultaneously in the server's JVM memory. The JVM treats classes loaded by different classloaders as entirely different entities, even if they share the exact same package and class name.

This typically happens when objects or function instances loaded by the previous deployment remain active in memory even after the standard undeploy command is executed, conflicting with the new deployment. Because this relies on lingering memory state, the issue is often intermittent and may not reproduce consistently across all environments.

Resolution

To resolve this issue, you must completely clear the JVM memory of the old classloader references before deploying the new code. A clean restart of the server processes is required.

Follow this sequence to safely apply the new deployment:

  1. Undeploy the old JAR: Remove the existing deployment from the cluster.

  2. Stop all servers: Bring down the application/cache servers to clear the JVM memory and purge any lingering active instances.

  3. Start the servers: Bring the servers back online with a clean memory state.

  4. Deploy the new JAR: Deploy the updated package

  5. Retest the application: Verify that the ClassCastException no longer occurs and the new functions operate as expected.