Singleton ejb?

Hi
          I need to wrapp an EJB service in a singleton service.
          But I don't know which class should be implements the weblogic.cluster.singleton.SingletonService interface (the home, remote or the bean).
          So what is the class that should implement this interface weblogic.cluster.singleton.SingletonService?
          Thanks in advance

EJB 3.0 only supports programmatic timer creation. The app can contain an enterprise bean component that supports timer callbacks (a "timed object" in spec parlance) , but the actual timers can only be created by calling TimerService.createTimer(). Given that :
1. There is no automatic timer creation as a result of deployment. Some developers approximate automatic timer creation
by calling a stateless session bean method from a web application initialization callback, but from the ejb container's perspective
that's just a normal run-time timer creation. In all cases you'll have as many timers as the number of times TimerService.createTimer() was called.
2. In a cluster, for each unique timer, each timer timeout callback will happen in only one server instance in the cluster. We do that
by using the underlying timer database and an ownership semantic that assigns each timer to a particular server instance. During
failover, ownership of timers owned by the failed server instance is reassigned to a healthy server instance. Note that this only applies
to timeout callbacks. All timers created by a bean are always visible to any instances of that bean in any server instance in the cluster.
In other words, getTimers() always returns the total number of timers associated with the bean component, even if the callbacks
happen in a different server instance in the cluster.
3. Each call to TimerService.createTimer() is unique across the cluster. However, the burden of ensuring that createTimer() is only
called once is on the application. EJB 3.1 will address this problem by adding "automatic timers". These are timers that are
specified via metadata (annotation or ejb-jar.xml) and are created automatically as a result of deployment.

Similar Messages

  • Singleton EJBs in Weblogic

    Hello everyone,
    I'm developing an application (with Weblogic 11gR1PS1) which needs a single point of access to get tickets for making requests. The numbers are sequential and cannot be 2 tickets with the same number, so Concurrency is an issue. Based on this we came up with 2 ideas:
    1- Creating a singleton EJB which will generate the tickets number to avoid 2 concurrent instances to generate the same number (if executing aproximately at the same time). Unfortunately I don't know how to do that with EJB 3.0 , I know that EJB 3.1 has a @Singleton annotation but that's not an option.
    2- Try to limit up the instances of a the generator Stateless Bean to 1 , making it a singleton. Unfortunately I don't know how to limit the number of instances in a pool of a specific EJB to 1, which is what is needed.
    I don't know which solution suits best, or even if there is a third one which any of you might know. Any suggestions will be appreciated!
    Thank you

    To limit the number of beans in the pool you can use the following:
    - create a deployment plan
    - create a file a deployment override weblogic-ejb-jar.xml and place this in the right directory (defined in the deployment plan)
    - add to the deployment override the following:
    <?xml version='1.0' encoding='UTF-8'?>
    <weblogic-ejb-jar xmlns="http://www.bea.com/ns/weblogic/10.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/10.0 http://www.bea.com/ns/weblogic/10.0/weblogic-ejb-jar.xsd">
    <weblogic-enterprise-bean>
    <ejb-name>NameOfYourEJB</ejb-name>
    <stateless-session-descriptor>
    <pool>
    <max-beans-in-free-pool>1</max-beans-in-free-pool>
    <initial-beans-in-free-pool>1</initial-beans-in-free-pool>
    </pool>
    </stateless-session-descriptor>
    </weblogic-enterprise-bean>
    Now there is only one bean in the pool. The problem with this is clients calling the EJB have to wait, until the EJB is released. This could have a negative effect on your response time of the application.
    Maybe you can create a normal singleton, for example,
    public class SomeSingleton {
    private static final MyObject myObject;
    private SomeSingletonl() {
    static {
    // create some instance of MyObject
    public static MyObject getMyObject() {
    return myObject;
    Then you can call this from your EJB

  • "Singleton" EJB Timer in GlassFish 2.1 cluster?

    Hi,
    suppose on a GlassFish 2.1 cluster (two instances on one machine) you deploy an ejb app which contains an ejb timer. The ejb timer executes every 60 seconds.
    Following questions come to my mind:
    1. After deployment do you have (the same) ejb timer on each instance (both using the same connection pool) ?
    2. If so, how it is guaranteed that every 60 seconds only one timer is executed?
    3. Is it possible to have a "singleton" timer for all instances in a cluster?
    Thx for your help.

    EJB 3.0 only supports programmatic timer creation. The app can contain an enterprise bean component that supports timer callbacks (a "timed object" in spec parlance) , but the actual timers can only be created by calling TimerService.createTimer(). Given that :
    1. There is no automatic timer creation as a result of deployment. Some developers approximate automatic timer creation
    by calling a stateless session bean method from a web application initialization callback, but from the ejb container's perspective
    that's just a normal run-time timer creation. In all cases you'll have as many timers as the number of times TimerService.createTimer() was called.
    2. In a cluster, for each unique timer, each timer timeout callback will happen in only one server instance in the cluster. We do that
    by using the underlying timer database and an ownership semantic that assigns each timer to a particular server instance. During
    failover, ownership of timers owned by the failed server instance is reassigned to a healthy server instance. Note that this only applies
    to timeout callbacks. All timers created by a bean are always visible to any instances of that bean in any server instance in the cluster.
    In other words, getTimers() always returns the total number of timers associated with the bean component, even if the callbacks
    happen in a different server instance in the cluster.
    3. Each call to TimerService.createTimer() is unique across the cluster. However, the burden of ensuring that createTimer() is only
    called once is on the application. EJB 3.1 will address this problem by adding "automatic timers". These are timers that are
    specified via metadata (annotation or ejb-jar.xml) and are created automatically as a result of deployment.

  • Singleton & EJB & Clustering

    Hello:
    although I have read information about this question in
    http://java.sun.com/developer/technicalArticles/Programming/singletons/ ,
    I continue having doubts.
    I need a class (A) called by stateless session beans to get next value from one previous value.
    This A class only performs queries from database ( using iBatis framework ) to get the next value, but doesn't store any value or state.
    My doubt is if I can have this class as a Singleton class , considering that it works in a clustered enviroment.
    As this A class is called by many session beans, I think that it's a good idea has a unique instance. But I have doubts about performance with this and the access to the resources ( only queries) .
    Can I use, in this case, Singleton pattern in clustered enviroment ?
    Thanks !

    The only thing is that this sounds like a class which is being used as a generator for primary keys.
    The concern is that you have two requests of the generator at the same time and, if the generator function is poorly coded, you then either have two non-unique primary keys, or somebody throws an exception.
    I would look and see if your database backend has some sort of sequence/auto-inc/generator functionality and hook into that (no point re-inventing the wheel)
    On the other hand, if you are trying to maintain some sort of database portability, you might be quicker having the inc larger than 1.
    e.g.
    on server#1: nextval = curval - (curval mod 3) + 3
    on server#2: nextval = curval - (curval mod 3) + 4
    on server#3: nextval = curval - (curval mod 3) + 5
    [Note the above strategy is not the most efficient, but will guarantee that the three servers _never_ produce duplicate IDs... how you would code some such is more fun.  It has the advantage that each server can lag behind in updates of the most recent value of curval without causing major issues]
    Other people may know a better way of solving the problem.
    If you are inventing your own wheel, i'd try testing it for duplicate values under heavy load as a critical test before release

  • Re-initialize EJB

    I have an implementation of an EJB that executes some code during the @PostConstruct. While my application is running, there are many instances of the EJB. Is there any way to force the application to call the code in @postConstruct (maybe with a different annotation) for each instance of the bean?
    This is what I would like to see happen.
    - bean gets initialized and calls @PostConstruct method during startup
    - application runs and uses bean for some time
    - application gets a trigger (from a timer or webservice) to call bean.reinitialize()
    - bean.reinitialize() tells the application to call the bean method with @PostConstruct (or a different annotation) once for each instance of the bean
    Does something like this exist with EJBs?

    r035198x wrote:
    user2695214 wrote:
    Wow, thanks for the reply. I was hoping it would not need to be overly complicated.
    In your first response you mentioned a "proper cache". What did you mean by this? Is there a some EJB construct for this or was there something more simple that you were referring to?If you are using JPA for persistence then your (persistence) provider would already come with some form of second cache implementation that you would need to configure or you can use existing caching APIs yourself like ehchache.Yep, a second-level cache would definitely be my first thought as well. that fits very well into the existing ejb/jpa infrastructure.
    that said, if you are working with some sort of non-jpa data, then you are looking at a custom cache situation. i would implement something like that using a JMX management bean (although initializing these in the ejb world is not as easy as it should be). you could probably also implement this using an ejb 3.1 singleton ejb.

  • EJB3 and the Singleton

    As per the defination of Singleton EJB
    A Singleton EJB is a session bean component that is instantiated once per application.
    In other words, all requests to the singleton will be routed to the single instance of the Singleton bean instance.
    ( I know taht a Stateless session bean is not applicable here , as the container might maintain a pool of
    these stateless bean instances
    But Can you please tell me how this is different from a normal Statefull Session Bean ??

    RaviKIran wrote:
    As per the defination of Singleton EJB
    A Singleton EJB is a session bean component that is instantiated once per application.Where did you find this definition? It contradicts the usual meaning of session bean as per EJB version 1 to 3.
    Note that singleton EJB are expected to be a feature included in the next version EJB 3.1. Whether it will be considered a session bean (application session vs user session) is open to debate, and is not strictly necessary.
    EDIT: my mistake: Sun does describe singleton EJB as being a new form of session bean. See this [enterprise tip|http://blogs.sun.com/enterprisetechtips/entry/a_sampling_of_ejb_3] .
    Edited by: jduprez on Oct 19, 2009 7:57 AM

  • Error when @Singleton in Glassfish v3 and weld. CDI not working for EJBs.

    Hello,
    I am getting the following error when deploying a web app with a SSB with the @Singleton annotation. If I use javax.ejb.Singleton I get the error. If I use @Stateless and @Singleton with javax.inject.Singleton, I don't.
    I use Glassfish v3 with weld.
    [#|2009-12-19T01:29:19.423+0100|SEVERE|glassfish|global|_ThreadID=16;_ThreadName=Thread-1;|The annotation symbol defined in super-class is not compatible with Session ejb ElaphusManager.
    symbol: TYPE location: class com.cervatoh2.elaphus.ejb.ElaphusManagerBean
    By the way,
    what is the right way to install weld into glassfish? To make @Named work I had to treat Glassfish v3 as if it was Tomat:
              <listener>
                        <listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>
                   </listener>
              <resource-env-ref>
    <description>Object factory for the CDI Bean Manager</description>
    <resource-env-ref-name>BeanManager</resource-env-ref-name>
    <resource-env-ref-type>javax.enterprise.inject.spi.BeanManager</resource-env-ref-type>
    </resource-env-ref>
    And also add weld-servle.jar to /WEB-INF/lib
    isn't Glassfish v3 supposed to have builtin weld support?
    thanks for any directions,
    Ignacio

    Well,
    I think I have understood what the problem is, and maybe also a patch for it.
    I have observed the exact same scenario as you guys.
    I think the problem is exposed by the statement in the status.conf file:
    rwConnStart message=All 1 wget requests did not return a valid vpnserver.conf
    The contents of the vpnserver.conf file in your case is:
    Which I also have observed. Now, I have just had a session, where one of my colleagues have a succesfull connection and I have a failed one. Now, his vpnserver.conf was:
    version=1
    msgtype=configuration
    conn xxxxx_rw
    presharedkey=xxxxxxxxxxxxxxxxxxx
    rightsubnet=xxx.xxx.xxx.xxx/xx
    remotelanip=xxx.xxx.xxx.xxx
    dnsserver=xxx.xxx.xxx.xxx
    domain=
    which is somewhat different. Mine was like the failing one you had. This made me think. The client is supposed to download vpnserver.conf via HTTPS and save it. Sometimes this goes wrong, and I think it is the router software that gets confused.
    It simply thinks you are trying to remote mgmt it and sends you the html to go to the welcome.html page. In my setup I have enabled HTTPS and disbaled Remote MGMT. So it should never ever think it is being remotely managed, but somehow it does that - doh!
    Thus, either the SW on the router is confused/buggy and this causes it to give you a HTML respond instead of the contents of the vpnserver.conf file. Another explanation could be that the wget tool has a problem, when a vpnserver.conf file already exists and then it doesn ensure to force download the file correctly or something.
    Nevertheless, I have two ways to solve this problem:
    1. Rebooting the router has worked for me, but is of course not nice
    2. Delete the local version of vpnserver.conf BEFORE you try to connect.
    The 2nd solution has not yet been verified to work in a broader scale, but we are trying to verify it.
    Please report if this helps you guys.
    Thanks, Jacob

  • Usage of Singleton within EJB Containter, recommended or not?

    Hi,
    in various articles I came across a statement that it is not a good practice to use the Singleton Pattern within the EJB Container. I recognize the problem when scaling an application to more application servers, which introduces the problem that every of this applications has a dedicated ClassLoader, so the sharing of the Singleton between this instances can be very complicated. I'm interrested in knowing if there are other issues that prevent the usage of the Singleton Pattern?
    Regarding scaling an application, can somebody share some expierences in scaling an application on oc4j? What problems may arise?
    thx in advance
    --hery                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Hi,
    in various articles I came across a statement that it is not a good practice to use the Singleton Pattern within the EJB Container. I recognize the problem when scaling an application to more application servers, which introduces the problem that every of this applications has a dedicated ClassLoader, so the sharing of the Singleton between this instances can be very complicated. I'm interrested in knowing if there are other issues that prevent the usage of the Singleton Pattern?
    Regarding scaling an application, can somebody share some expierences in scaling an application on oc4j? What problems may arise?
    thx in advance
    --hery                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Can I Use Singletone  Pattren for DAO in Stateless EJB?

    Hi friends,
    I have a design in which i am creating an Business Layer using EJB (Stateless). In my case i have only read only to DataBase and at one case where i will be updating the database. But my application will be accessed by many concurrent users.
    My problem is if i create a DAO with singleton pattren then it will be returning the same instance to all the person who access the DB. So if one person is reading the database and at the same moment one more person request for update since the DAO is singleton object will there be any conflict?
    Reply soon

    Hi Martin.S
    Thanks for your suggestion.
    U Asked
    You need to think about why have you have made your DAO a Singleton. You need to ask yourself, SHOULD it be a Singleton? It may be valid decision but I find that doubtful. Singleton DAO's suit only limited set of circumstances. Why i decided to use singleton pattren was :
    Since i am using session bean and if i won't use Singleton pattren and
    If my app was used by say 1000 users
    Then 1000 Dao instaces whould be created!
    The App Server will have 1000 refrences which may be a performance issue and may slow down the server due to more usage of server resource. So i need to know weather is it a good idea to use the Singleton pattren for DAO when using SessionBeans?
    And one more doubt I have Martin
    If i use One Dao Class Per One Table Then How about the factories if i use singleton? Need to create so many factories as DAO's? *reply
    Also i think if i use Single DAO per Table and if i have say 1 user accessing the DAO and he is in the Middle of his execution and user 2 requests for the same DAO once again the situation is worse! Am i right?
    So I think Singleton pattren comes into handy only when one person is accessing the DAO at a time. After he completes then only we can give access to some one else.
    And also while Using EJB's Using syncronized DAO is not preffered since EJB's are for multiple access
    So do you have any solution for the same? Currently I am using ordinary DAO and creating multiple instances in the Session Bean.
    Is there any way to Use SingleTon Pattren inside SessionBean?
    Reply
    A Singleton DAO would be valid choice when you are doing performance/throughput optimisation for read only access to dataset which you have cached for speed, but need to ensure only one copy exists for memory efficiency.One more query martin,
    How can we use it for read only access to a data set?
    For example i have a DAO which queries and returns some result sets based on some input value given by the user
    Now take a senario1: User1 supplys some input value and executes method1() and he is in the middle.
    User2 comes in and acess the same method1() with different input value
    Since it is a SingleTon Pattren The User2 will get same refrence
    So user1 will get the result set that is having the input parameters of user2. Right?????????
    So my inference is we cannot use singelton pattren for concurrent acess of the DAO.What do you say
    Please Reply Martin

  • EJB 3.1 @Singleton with @Startup causes @PostConstruct to be called twice...

    I have been working on initializing a some elements in the @PostConstruct annotated method within an EJB that is already annotated as @Singleton.  I decided that I wanted the initialization to be done when the EJB is deployed so I added the @Startup.  Both the constructor and @PostConstruct method is getting called twice.  Can someone please explain to me why it appears the EJB is being initialized twice and if there is a way to prevent the @PostConstruct method from being called twice?
    Many thanks,
    - Joe

    Is this with GlassFish?

  • Singletons in EJB Container

    I'm working with an existing application that uses "traditional" Singletons in the EJB continer (static instance variable to contain the state and guarded access to the state). These singletons are running in the EJB container and I need to get rid of them and replace them with something that will work in a clustered environment.
    Basically, there are single instances of resources that are being shared across multiple EJB components. These resources are not serializable. Short of a complete re-write of the entire application (which, BTW, is not feasible), how can these resources be shared in the EJB Container.
    I've tried adding them to the naming context, but that's not working because they are not serializable. Is there any place I can park these resources so that all my EJBs have access?
    I have a feeling there is no simple solution to this problem.
    TG

    Well, you might have already thought of this, but the traditional way would be to store the resource in a database ?

  • When not using EJBs can I make BD a Singleton and cache facade instances?

    Hi,
    In an application which does not use EJBs can I make BD(Business Delegate) a singleton?
    I was very sure about doing this but when I tried Google on the same subject the answers were'nt supportive of this but that was in the context of applications which used EJBs. And also item 4 in Effective Java isnt very supportive of caching Objects at the drop of a hat.
    When not using EJBs would it be an unnecessary thing to make BD a singleton and cahce Facade instances in a BD and DAO instances in a Facade? I am planning to use a array based blocking bounded buffer for the purposes of caching. Or would it be better to make both BD and a facade as SIngletons and just cache DAOs in a Facade?
    Any suggestion would be of good help to me.
    Thanks a lot.

    Not sure I understand all your design, but you seem
    to describe an architecture where requests are queued
    and handled serially.Sorry if I messed up while explaining it. No, it will not be handled serially. Since the BD is a singleton multiple threads can pass messages to it simulteanously, a bit like an object of the Action class in Struts. Since I dont see having any synchronized methods in a BD requests will be handled simulteanously.
    The impact on throughput of handling requests
    serially (as opposed to parallelizing them) probably
    outweights by far the cost of instantiating one more
    object per request...Yes, I understand that but as I explained above the reqests wont be handled serially.
    To be more clear, I am thinking of using any one of these two things:
    1) BD(Singleton)-->Facade(Singleton, caches DAOs in a thread safe data structure)
    2)1) BD(Singleton, caches Facade instances in a thread safe data structure)-->Facade(caches DAOs in a thread safe data structure).
    the thread safe data structure I am planning to have is a array based bounded buffer which blocks using wait and notify mechanism.
    Thank you for the reply.

  • Singleton life-cycle in EJBs

    This is a general question that I have about the use of a singleton class from an EJBs.
    I want to create a cache in the form of a singleton (suppose for now, no server clustering). The goal of this cache would be to speed access to a database. Different users logging into the system would access this single data point to get cached db info relevant to their privilages instead of resorting to database calls all the time. Suppose I want to use stateless session EJBs.
    How do I make sure that after a creation of a Singleton in the VM, it doesn't go away when a particular ejb object gets' destroyed by the container? How does the lifecycle of the EJB relate to that of this cache? Given that the VMs garbage collector does not scrap my cache unless I have a reference to it, how do I maintain such a reference across multiple stateless session beans?
    Any light on this issue would be really appreciated!
    Thanks,
    Alex

    How about binding your cache object to JNDI?

  • Ejb hotdeploy, classloading & singleton

    I have the following doubt about hot-deploy, classloading & singletons.
    Let´s assume I have a sessionbean which accesses a singleton. As far as I understand
    hot-deploy in weblogic, during a hot-deployment, a sessionbean instance currently
    engaged in a transaction is not unloaded untill the transaction is completed.
    New transactions however would access the newly deployed & loaded instances of
    the new version of my session bean.
    Am I correct to assume that, if this is the case, several instances of my singleton
    may exist at a certain moment in the same JVM (I am not talking about clusters,
    but about execution threads).

    Hi Seth
    Are you hot redeploying the entire application? Is the singleton class
    packaged with the application?Yes the singleton is packaged with the application. It´s actually the Bussiness
    Delegate.
    >
    Thanks.
    Seth
    "Sven van ´t Veer" wrote:
    I have the following doubt about hot-deploy, classloading & singletons.
    Let´s assume I have a sessionbean which accesses a singleton. As faras I understand
    hot-deploy in weblogic, during a hot-deployment, a sessionbean instancecurrently
    engaged in a transaction is not unloaded untill the transaction iscompleted.
    New transactions however would access the newly deployed & loaded instancesof
    the new version of my session bean.
    Am I correct to assume that, if this is the case, several instancesof my singleton
    may exist at a certain moment in the same JVM (I am not talking aboutclusters,
    but about execution threads).

  • How to create a cache for JPA Entities using an EJB

    Hello everybody! I have recently got started with JPA 2.0 (I use eclipseLink) and EJB 3.1 and have a problem to figure out how to best implement a cache for my JPA Entities using an EJB.
    In the following I try to describe my problem.. I know it is a bit verbose, but hope somebody will help me.. (I highlighted in bold the core of my problem, in case you want to first decide if you can/want help and in the case spend another couple of minutes to understand the domain)
    I have the following JPA Entities:
    @Entity Genre{
    private String name;
    @OneToMany(mappedBy = "genre", cascade={CascadeType.MERGE, CascadeType.PERSIST})
    private Collection<Novel> novels;
    @Entity
    class Novel{
    @ManyToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST})
    private Genre genre;
    private String titleUnique;
    @OneToMany(mappedBy="novel", cascade={CascadeType.MERGE, CascadeType.PERSIST})
    private Collection<NovelEdition> editions;
    @Entity
    class NovelEdition{
    private String publisherNameUnique;
    private String year;
    @ManyToOne(optional=false, cascade={CascadeType.PERSIST, CascadeType.MERGE})
    private Novel novel;
    @ManyToOne(optional=false, cascade={CascadeType.MERGE, CascadeType.PERSIST})
    private Catalog appearsInCatalog;
    @Entity
    class Catalog{
    private String name;
    @OneToMany(mappedBy = "appearsInCatalog", cascade = {CascadeType.MERGE, CascadeType.PERSIST})
    private Collection<NovelEdition> novelsInCatalog;
    The idea is to have several Novels, belonging each to a specific Genre, for which can exist more than an edition (different publisher, year, etc). For semplicity a NovelEdition can belong to just one Catalog, being such a Catalog represented by such a text file:
    FILE 1:
    Catalog: Name Of Catalog 1
    "Title of Novel 1", "Genre1 name","Publisher1 Name", 2009
    "Title of Novel 2", "Genre1 name","Pulisher2 Name", 2010
    FILE 2:
    Catalog: Name Of Catalog 2
    "Title of Novel 1", "Genre1 name","Publisher2 Name", 2011
    "Title of Novel 2", "Genre1 name","Pulisher1 Name", 2011
    Each entity has associated a Stateless EJB that acts as a DAO, using a Transaction Scoped EntityManager. For example:
    @Stateless
    public class NovelDAO extends AbstractDAO<Novel> {
    @PersistenceContext(unitName = "XXX")
    private EntityManager em;
    protected EntityManager getEntityManager() {
    return em;
    public NovelDAO() {
    super(Novel.class);
    //NovelDAO Specific methods
    I am interested at when the catalog files are parsed and the corresponding entities are built (I usually read a whole batch of Catalogs at a time).
    Being the parsing a String-driven procedure, I don't want to repeat actions like novelDAO.getByName("Title of Novel 1") so I would like to use a centralized cache for mappings of type String-Identifier->Entity object.
    Currently I use +3 Objects+:
    1) The file parser, which does something like:
    final CatalogBuilder catalogBuilder = //JNDI Lookup
    //for each file:
    String catalogName = parseCatalogName(file);
    catalogBuilder.setCatalogName(catalogName);
    //For each novel edition
    String title= parseNovelTitle();
    String genre= parseGenre();
    catalogBuilder.addNovelEdition(title, genre, publisher, year);
    //End foreach
    catalogBuilder.build();
    2) The CatalogBuilder is a Stateful EJB which uses the Cache and gets re-initialized every time a new Catalog file is parsed and gets "removed" after a catalog is persisted.
    @Stateful
    public class CatalogBuilder {
    @PersistenceContext(unitName = "XXX", type = PersistenceContextType.EXTENDED)
    private EntityManager em;
    @EJB
    private Cache cache;
    private Catalog catalog;
    @PostConstruct
    public void initialize() {
    catalog = new Catalog();
    catalog.setNovelsInCatalog(new ArrayList<NovelEdition>());
    public void addNovelEdition(String title, String genreStr, String publisher, String year){
    Genre genre = cache.findGenreCreateIfAbsent(genreStr);//##
    Novel novel = cache.findNovelCreateIfAbsent(title, genre);//##
    NovelEdition novEd = new NovelEdition();
    novEd.setNovel(novel);
    //novEd.set publisher year catalog
    catalog.getNovelsInCatalog().add();
    public void setCatalogName(String name) {
    catalog.setName(name);
    @Remove
    public void build(){
    em.merge(catalog);
    3) Finally, the problematic bean: Cache. For CatalogBuilder I used an EXTENDED persistence context (which I need as the Parser executes several succesive transactions) together with a Stateful EJB; but in this case I am not really sure what I need. In fact, the cache:
    Should stay in memory until the parser is finished with its job, but not longer (should not be a singleton) as the parsing is just a very particular activity which happens rarely.
    Should keep all of the entities in context, and should return managed entities form mehtods marked with ##, otherwise the attempt to persist the catalog should fail (duplicated INSERTs)..
    Should use the same persistence context as the CatalogBuilder.
    What I have now is :
    @Stateful
    public class Cache {
    @PersistenceContext(unitName = "XXX", type = PersistenceContextType.EXTENDED)
    private EntityManager em;
    @EJB
    private sessionbean.GenreDAO genreDAO;
    //DAOs for other cached entities
    Map<String, Genre> genreName2Object=new TreeMap<String, Genre>();
    @PostConstruct
    public void initialize(){
    for (Genre g: genreDAO.findAll()) {
    genreName2Object.put(g.getName(), em.merge(g));
    public Genre findGenreCreateIfAbsent(String genreName){
    if (genreName2Object.containsKey(genreName){
    return genreName2Object.get(genreName);
    Genre g = new Genre();
    g.setName();
    g.setNovels(new ArrayList<Novel>());
    genreDAO.persist(t);
    genreName2Object.put(t.getIdentifier(), em.merge(t));
    return t;
    But honestly I couldn't find a solution which satisfies these 3 points at the same time. For example, using another stateful bean with an extended persistence context (PC) would work for the 1st parsed file, but I have no idea what should happen from the 2nd file on.. Indeed, for the 1st file the PC will be created and propagated from CatalogBuilder to Cache, which will then use the same PC. But after build() returns, the PC of CatalogBuilder should (I guess) be removed and re-created during the succesive parsing, although the PC of Cache should stay "alive": shouldn't in this case an exception being thrown? Another problem is what to do when the Cache bean is passivated. Currently I get the exception:
    "passivateEJB(), Exception caught ->
    java.io.IOException: java.io.IOException
    at com.sun.ejb.base.io.IOUtils.serializeObject(IOUtils.java:101)
    at com.sun.ejb.containers.util.cache.LruSessionCache.saveStateToStore(LruSessionCache.java:501)"
    Hence, I have no Idea how to implement my cache.. Can you please tell me how would you solve the problem?
    Many thanks!
    Bye

    Hi Chris,
    thanks for your reply!
    I've tried to add the following into persistence.xml (although I've read that eclipseLink uses L2 cache by default..):
    <shared-cache-mode>ALL</shared-cache-mode>
    Then I replaced the Cache bean with a stateless bean which has methods like
    Genre findGenreCreateIfAbsent(String genreName){
    Genre genre = genreDAO.findByName(genreName);
    if (genre!=null){
    return genre;
    genre = //Build new genre object
    genreDAO.persist(genre);
    return genre;
    As far as I undestood, the shared cache should automatically store the genre and avoid querying the DB multiple times for the same genre, but unfortunately this is not the case: if I use a FINE logging level, I see really a lot of SELECT queries, which I didn't see with my "home made" Cache...
    I am really confused.. :(
    Thanks again for helping + bye

Maybe you are looking for

  • HT1535 I don't have a computer anymore. How can I sync my it ouch music to my new iPad?

    My computer crashed and I am trying to get by with just my it ouch and iPad. How can I sync music from one device to the other wirelessly? Thanks

  • Missing photos randomly in iPhoto

    Read a thread further down and I've tried all those. It started about 2 weeks ago. Events missing all over the place (4619 photos in total divided into events). Before this started I copied the iPhoto Library file onto an external drive 18GB approx a

  • Installing Oracle Database Express Edition 11g on UBUNTU

    Hello everyone, I want to install Oracle Database Express Edition 11g on UBUNTU. I followed the steps from this link created by Dude: https://forums.oracle.com/thread/2303639?start=0&tstart=0 My problem becomes when I type in from the terminal: sudo

  • Messages showing up as phone numbers not as names

    just updates to the latest Mountain Lion today.  In Messages, my list of chats that are sent via iMessage are now showing up listed with their iPhone number or their apple id email, not with their names.  In the past, Messages would match these up wi

  • Request PL/SQL article

    Hi,everyone,i'm a beginner of PL/SQL£¬ Who can recommend a pl/sql article to me. Thanks.