title: Concurrent access causes ClassCastException (X cannot be cast to X), or how to resolve such class loading problems in JBoss
body: <p>I have a problem concerning JBoss and class loading.</p>
  
  <p>Here is the configuration I am working with. I have two instances of <strong>JBoss 4.2.3.GA</strong> on the same server. On each instance an application is running, and these applications are communicating with each other. There is an utility class, packed in both applications archives. This utility class is strictly the same in both applications.</p>
  
  <p>This usually works fine, but in particular situations, I get <strong>ClassCastException</strong>. The case is the following:</p>
  
  <p>A user is using a web application, which calls the application on the first JBoss instance (let's call it the application A). And application A calls the application B (on the second instance). This particular call takes several seconds to succeed.</p>
  
  <p>If another user is trying to use the web application in a similar context (call to application A, which calls application B), and if this call happens during the first user call, I get systematically a ClassCastException : <code>X cannot be cast to X</code> (where X is my utility class, shared by both applications).</p>
  
  <p>I found some information, and I deduced it was a class loading problem. Indeed, in this particular context of concurrent calls, my utility class is not loaded by the same class loader. I put a print command to see which class loader is used. In usual behavior, <strong>org.jboss.mx.loading.UnifiedClassLoader3</strong> is used to load classes. In the particular described above, the application B seems to used a different class loader for the second user. My print command gave me the following:</p>
  
  <pre><code>WebappClassLoader
    delegate: false
    repositories:
      /WEB-INF/classes/----------&gt; Parent Classloader:java.net.FactoryURLClassLoader@de8209
  </code></pre>
  
  <p>My guess is that application B return an instance of my utility class loaded by this <strong>WebappClassLoader</strong>, and application A (which is using UnifiedClassLoader3) cannot cast it.</p>
  
  <p>But i don't get why the UnifiedClassLoader3 cannot be used in this case, on application B. And why is this WebappClassLoader used ?</p>
  
  <p>All I know about the class loading configuration in my JBoss instances is that class loading isolation is used, the following configuration is used for both applications :</p>
  
  <pre><code>&lt;jboss-app&gt;
    &lt;module-order&gt;strict&lt;/module-order&gt;  
    &lt;loader-repository&gt;applicationAorApplicationB.ear&lt;/loader-repository&gt;
  &lt;/jboss-app&gt;
  </code></pre>
  
  <p>Do you have any advice to resolve this problem? How can I configure jboss class loader to avoid these class cast exception?</p>
  
  <p>I precise that there is no hot deployment: I clean the server each time I deploy the applications.</p>