Question

I tried implementing a singleton class method , which is invoked by a filter class. The filter class and the rest of the classes , are added to WLS as a shared library.

And i have two separate web apps running - servlets with filter - both on the same managed server.

So everything is working fine except , the singleton is getting instantiated twice . plz find below the code snippet.

public class Test
{
   private static Test ref ;

   private DataSource X;  
   static int Y;
   long Z ;   


   private Test ()
   {
      // Singleton 
   Z= 100 ;
   }

   public static synchronized Test getinstance()  throws NamingException, SQLException
   {
      if(ref == null)
      {         
         ref = new Test() ;         
         InitialContext ic = new InitialContext();

         ref.X = (DataSource)ic.lookup ("jdbc/Views");
      } 
      return ref ;    
   }

   public Object clone()throws CloneNotSupportedException
   {
       throw new CloneNotSupportedException(); 
   }

   public int sampleMethod (int X) throws SQLException
   {
   }

}

Filter method:

public final class Filter implements Filter
{
 public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException
 {
  try
  {  
   Test ref = Test.getinstance();
   log.logNow(ref.toString());
   .......

  }
 }
}

In the log am getting two different references - say

Test@f1a2e06 Test@f180f10

Am i doing something wrong here ? Any help would be great.

Was it helpful?

Solution

A servlet container uses different classloaders for different application. So I don't believe it is possible to share an instance. What you can do is perhaps register the instance via JNDI.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top