Search code examples
javasingletonjavabeans

Java Singleton bean creating multiple instances of a list


I am at a loss on what is going on here. I have a singleton bean that contains a list. When I add items to the list, the content is always consistent. However, when I call a get on that list from a different service, it returns an empty list with a different java id. Somehow the singleton bean has two different instances of the contained list based on who is calling.

Here is how the class is defined:

@Startup
@LocalBean
@DependsOn({ "classnameremoved" })
@Dependent
@Singleton
public class SomeManager
{
    private List<someType> aList = new ArrayList<someType>();

    public List<someType> getListData()
    {
         List<someType> returnList = new ArrayList<someType>();
         synchronized (aList)
         {
             returnList.addAll(aList);
         }

         return returnList;
    }

    public void handleCreatedEvent(Data someData)
    {
        synchronized (aList)
        {
             aList.add(someData);
        }
    }
}

The differences between the two are this:

The add method is called from a bean that listens for new messages and calls the appropriate handler. The get is called from another bean that handles the data after the fact. When I call from the two one after another, the list has a different ID and is not the same object. I can't figure out what this is happening.

In both beans I have the class above included with the following line:

@EJB
private SomeManager someManager;

The other two classes have the following annotations:

This class always has the proper data in the list and is not cleared over repeat tests.

@Singleton
@Startup
@LocalBean
@DependsOn("some class")
public class MessageListener ...

This class always get an empty list back

@Stateless
@LocalBean
@javax.ejb.TransactionManagement(javax.ejb.TransactionManagementType.BEAN)
public class GetClass ...

Any hints as to what is going on is much appreciated. This is all on a single local machine.


Solution

  • You may want to see this resource.

    http://www.oracle.com/technetwork/articles/java/singleton-1577166.html