javasingletoneclipse-rap

RAP Application Singleton


So, I've been reading about RAP applications and I can't stop wondering how should I create static variables only for the current session (in case that are more than one person accessing the application at the same time). I have read about SingletonUtil. Yet, I have a few questions about it.

1- Should I create one SessionSingleton for the application? Or should I create one SessionSingleton for each class I have on my application (I know it sounds dumb and I probably should create just one SessionSingleton for the application, but... Just making sure).

2- Once I create this Singleton, each user (or session) will have access only to their static fields, correct? it's right to affirm that they won't get data from other static fields from different sessions? (Let's assume I am creating a shopping cart. It would be impossible to do so if custumers could see the shopping cart from another session).


Solution

  • To re-iterate what Timothy Truckle said, you should stay away from singletons as much as possible.

    In web applications, static fields implicitly have application scope because each web application is isolated from others through a separate class loader. That is, your exemplary shopping cart would be shared among all sessions/users of the same web application. This is usually not what you want.

    To provide a shopping cart for each session you could use the SingletonUtil to

    Either like this

    SoppingCart cart = SingletonUtil.getSessionInstance( ShoppingCart.class );
    

    or

    SoppingCart cart = SingletonUtil.getUniqueInstance( ShoppingCart.class, session );
    

    The first variant uses the current UI session - the one that is assigned to the currently executing request thread.

    The second variant requires you to provide the UI session for which the singleton should be obtained/created. Use this if you are, for example, running the code from a background thread that was started from a UI session.

    UISession session = RWT.getUISession( display );
    
    Thread thread = new Thread( this::calcualteItemsInShoppingCart );
    thread.start();
    
    void calculateItemsInShopingCart() {
      SoppingCart cart = SingletonUtil.getUniqueInstance( ShoppingCart.class, session );
      // use cart...
    }
    

    In general, use (session/application) singletons only as a last resort. They will become a burden sooner or later. Try hard to design your code so that you can create the shopping cart, or example in the entry point, and pass it on to those parts of the code that need access to it.

    Note that in RAP, there may be multiple UI sessions (one per browser window/tab) per servlet session.

    See also the Singletons and Static Fields in RAP chapter of the RAP documentation.

    Does that answer your question?