Singletone inheritanc​e

Hi!
I implemented a framework based on pluggins, in which there is a GeneralPluggin and five child pluggins that adds some funcionality. I realized that these pluggins coorespond to the singleton pattern so I used the Goop tool to create them in this way. Due to they inherit from a not singletone class to use the parent vis I made public the "Get_Instance" vi despite I knew it was wrong, the problem with it is that the program creates some instances with the same reference, but ones are filled with the correct data and the other are empty. To solve this issue I'm trying to redo the Genericpluggin class in the singletone pattern and inherit from it again.
But I have some questions, how can the child classes access to the parent atributes and vi's? And how can they know which class is the proper child class which is calling the paret funcionality if there is not " class reference In "  in the vi, as it is singleton....
For instance in a normal class you wire the child class calling a parent vi, and as you wire the class in, it knows which child function should call but in this case... I'm a bit confused!!!
Thanks in advance!!!

Hm sorry for my comment,
I still try to learn LV OOP by desperately trying to understand these posts (https://decibel.ni.com/content/docs/DOC-13462)... I did not even realize from the NI post that your class works without class wires afterwards.
Without a class wire or something like this I can not imagine a way to call parent functions on children. Maybe just inherit the function by creating a Vi calling the GetInstance and then the parent function as a (dumb) work-around.

Similar Messages

  • Can not access the Instance Data of a Singleton class from MBean

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

  • MDB and Singleton

    I have a MDB that receives data from a JSM queue in XML format. After converting the XML to proper Value Objects using JAXB, it calls a DAO.
    We have configure the App server (WLS 8.1)to have 10 MDB in the pool.
    The DAO is a singleton with a none static private data member that holds the DataSource.
    The DAO.add() operation gets connection from the data source and performs the add.
    When we put one msg on the JMS queue we see the transaction time in DAO.add() is an about 1 sec.
    When we put 30 msgs on the JMS queue we see 10 threads accessing the singleton instance of the DAO.
    I was hoping to see the DB transactions started by these 10 threads would be executed in parallel they way threaded operations should behave considering the context switching factor however what I am seeing from the log files is that the DB transactions are serialized meaning they get executed one at a time!!?? Therefore it takes 10 sec for the 10 threads to complete their work. I was expecting to see something like 3 to 4 sec for all 10 thread to complete the add operation.
    Anyone has any ideas? Could it be that the Datasource is a private member of the Singleton DAO and each thread who calls the DAO.add() gets queued up to get access to the Data Source?
    Any idea would be great.
    Thanks.

    Thanks for your answer,
    So you never load classes then from configuration file? For example lets say you are processing xml message and for each xml message tag name you have in configuration file the appropriate class to handle such a message. Instead of configuration files would you then just store the values in a map of messageTagName to JNDI name?
    Thanks
    http://www.ellasweddingfavors.com
    Message was edited by:
    fkzeljo
    Ellas Wedding Favors

  • How do i use classloaders to create singletons

    I have some code that correctly creates a singleton because the code runs within a clients vm , and there should only be instance of the class per user. But for testing purposes I would like to mimic two users, to do this they each require their own instance of the singleton. I have read that using custom classloaders there could be one instance of each singleton per classloader, but dont understand how to do this. Can someone give me an example

    As I understand it you are simulating what amounts to
    a number of instances running in separate JVMs
    (probably on different machines) by running multiple
    instances in the same JVM. The natural way to do this
    would be to start multiple threads, each representing
    the action of one of these clients. (To do it
    sequentially would be a very poor test, since you
    need to cope with multiple, simultaneous
    activities).Yes, correct
    >
    The use of ThreadLocal enables you to have a separate
    instance of the "singleton" class for each thread.
    Any calls to the getInstance() method in the class
    made within one of the threads will return the
    details of the user "logged in" on that thread.
    Ok,fine but Ive simplified the use case there are a number of singletons involved (most of which are not called directly by the test code but by each other) , all of these would have to be identified and modified.
    InheritableThreadLocal extends this by passing the
    same instance to any child threads formed in one of
    these threads after initially intanciating an
    instance in a Thread (quite possibly uneccessary).Not needed, (thanks for explaining it though)
    And you can, if you wish, leave this in in the
    production version providing you do the login in the
    root thread of the client JVM.
    We do not want to allow the client to do such things.
    This, I have to say, would be a vastly less messy
    solution (and a much milder distortion between test
    and production) than anything based on ClassLoaders
    could possibly provide. Using custom class loaders
    quickly gets very messy indeed.
    I was hoping that by having two threads, each defining their own instance of a classloader it would get round the singleton behaviour and this is the only problem I am trying to solve. Obviously this would not be desirable in production but if it solves my testing problem Ill be happy, whether or not this is possible I still cant ascertain.
    If you have existing code you aren't allowed to
    change, then the best solution is probabllly to run
    multiple JVMs, exactly as in the real live case.We are using junit and taking advantage of its reporting facilities,ant integration and so on. If I was to have two JVMs I would have to split my test into two coorporating tests that would have to run in parallel but as far as Junit was concerned were two seperate tests, I can see this causing problems with reporting and causing side effects on other tests if something failed. Im aware that I am not really writing 'unit' tests in the strict test but the Junit framework provides advantages over plain old java.

  • Shared Connection Pool via Singleton

    I have just started to learn Java (more jsp & servlets) and have been going through "Core Servlets and Java Server Pages" and in there is stuff on connection pooling. The author provides a good a connection pool servlet that can be shared, but as I'm new and don't fully understand how everything works (got a basic idea).
    How do i go about making the following code accessiable via a singleton class?
    ConnectionPool Class
    package sco;
    import java.sql.*;
    import java.util.*;
    /** A class for preallocating, recycling, and managing
    *  JDBC connections.
    *  <P>
    *  Taken from Core Servlets and JavaServer Pages
    *  from Prentice Hall and Sun Microsystems Press,
    *  http://www.coreservlets.com/.
    *  &copy; 2000 Marty Hall; may be freely used or adapted.
    public class ConnectionPool implements Runnable {
      private String driver, url, username, password;
      private int maxConnections;
      private boolean waitIfBusy;
      private Vector availableConnections, busyConnections;
      private boolean connectionPending = false;
      public ConnectionPool(String driver, String url,
                            String username, String password,
                            int initialConnections,
                            int maxConnections,
                            boolean waitIfBusy)
          throws SQLException {
        this.driver = driver;
        this.url = url;
        this.username = username;
        this.password = password;
        this.maxConnections = maxConnections;
        this.waitIfBusy = waitIfBusy;
        if (initialConnections > maxConnections) {
          initialConnections = maxConnections;
        availableConnections = new Vector(initialConnections);
        busyConnections = new Vector();
        for(int i=0; i<initialConnections; i++) {
          availableConnections.addElement(makeNewConnection());
      public synchronized Connection getConnection()
          throws SQLException {
        if (!availableConnections.isEmpty()) {
          Connection existingConnection =
            (Connection)availableConnections.lastElement();
          int lastIndex = availableConnections.size() - 1;
          availableConnections.removeElementAt(lastIndex);
          // If connection on available list is closed (e.g.,
          // it timed out), then remove it from available list
          // and repeat the process of obtaining a connection.
          // Also wake up threads that were waiting for a
          // connection because maxConnection limit was reached.
          if (existingConnection.isClosed()) {
            notifyAll(); // Freed up a spot for anybody waiting
            return(getConnection());
          } else {
            busyConnections.addElement(existingConnection);
            return(existingConnection);
        } else {
          // Three possible cases:
          // 1) You haven't reached maxConnections limit. So
          //    establish one in the background if there isn't
          //    already one pending, then wait for
          //    the next available connection (whether or not
          //    it was the newly established one).
          // 2) You reached maxConnections limit and waitIfBusy
          //    flag is false. Throw SQLException in such a case.
          // 3) You reached maxConnections limit and waitIfBusy
          //    flag is true. Then do the same thing as in second
          //    part of step 1: wait for next available connection.
          if ((totalConnections() < maxConnections) &&
              !connectionPending) {
            makeBackgroundConnection();
          } else if (!waitIfBusy) {
            throw new SQLException("Connection limit reached");
          // Wait for either a new connection to be established
          // (if you called makeBackgroundConnection) or for
          // an existing connection to be freed up.
          try {
            wait();
          } catch(InterruptedException ie) {}
          // Someone freed up a connection, so try again.
          return(getConnection());
      // You can't just make a new connection in the foreground
      // when none are available, since this can take several
      // seconds with a slow network connection. Instead,
      // start a thread that establishes a new connection,
      // then wait. You get woken up either when the new connection
      // is established or if someone finishes with an existing
      // connection.
      private void makeBackgroundConnection() {
        connectionPending = true;
        try {
          Thread connectThread = new Thread(this);
          connectThread.start();
        } catch(OutOfMemoryError oome) {
          // Give up on new connection
      public void run() {
        try {
          Connection connection = makeNewConnection();
          synchronized(this) {
            availableConnections.addElement(connection);
            connectionPending = false;
            notifyAll();
        } catch(Exception e) { // SQLException or OutOfMemory
          // Give up on new connection and wait for existing one
          // to free up.
      // This explicitly makes a new connection. Called in
      // the foreground when initializing the ConnectionPool,
      // and called in the background when running.
      private Connection makeNewConnection()
          throws SQLException {
        try {
          // Load database driver if not already loaded
          Class.forName(driver);
          // Establish network connection to database
          Connection connection =
            DriverManager.getConnection(url, username, password);
          return(connection);
        } catch(ClassNotFoundException cnfe) {
          // Simplify try/catch blocks of people using this by
          // throwing only one exception type.
          throw new SQLException("Can't find class for driver: " +
                                 driver);
      public synchronized void free(Connection connection) {
        busyConnections.removeElement(connection);
        availableConnections.addElement(connection);
        // Wake up threads that are waiting for a connection
        notifyAll();
      public synchronized int totalConnections() {
        return(availableConnections.size() +
               busyConnections.size());
      /** Close all the connections. Use with caution:
       *  be sure no connections are in use before
       *  calling. Note that you are not <I>required</I> to
       *  call this when done with a ConnectionPool, since
       *  connections are guaranteed to be closed when
       *  garbage collected. But this method gives more control
       *  regarding when the connections are closed.
      public synchronized void closeAllConnections() {
        closeConnections(availableConnections);
        availableConnections = new Vector();
        closeConnections(busyConnections);
        busyConnections = new Vector();
      private void closeConnections(Vector connections) {
        try {
          for(int i=0; i<connections.size(); i++) {
            Connection connection =
              (Connection)connections.elementAt(i);
            if (!connection.isClosed()) {
              connection.close();
        } catch(SQLException sqle) {
          // Ignore errors; garbage collect anyhow
      public synchronized String toString() {
        String info =
          "ConnectionPool(" + url + "," + username + ")\n" +
          ", available=" + availableConnections.size() + "\n" +
          ", busy=" + busyConnections.size() + "\n" +
          ", max=" + maxConnections;
        return(info);
    ScoPool Class (singleton to access the connection pool)
    package sco;
    public class ScoPool extends ConnectionPool {
      private ScoPool pool = null;
      private ScoPool() {
        super(); // Call parent constructor
      public static synchronized ScoPool getInstance() {
        if(pool == null) {
          pool = new ScoPool();
        return(pool);
    }Please help a newbie.

    Figured it out.
    package sco;
    import java.sql.SQLException;
    public class ScoPool extends ConnectionPool {
      private static ScoPool pool;
      private ScoPool(String driver, String url, String username, String password,
                      int initialConnections, int maxConnections, boolean waitIfBusy) throws SQLException {
        super(driver, url, username, password, initialConnections, maxConnections, waitIfBusy); // Call parent constructor
      public static synchronized ScoPool getInstance() {
        if(pool == null) {
          String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
          String url = "jdbc:microsoft:sqlserver://MIM-W0432:1433;DatabaseName=sco";
          String username = "sco_user";
          String password = "123";
          int initCon = 5;
          int maxCon = 10;
          boolean waitIfBusy = true;
          try {
            pool = new ScoPool(driver, url, username, password, initCon, maxCon, waitIfBusy);
          catch(SQLException sqle) {
        return pool;
    }

  • How can I fix a xquery resulting error ORA-19279: XPTY0004 - XQuery dynamic type mismatch: expected singleton sequence  - got multi-item sequence

    Hello,
    How can I improve the XQuery below in order to obtain a minimised return to escape from both errors ORA-19279 and ORA-01706?
    XQUERY for $book in  fn:collection("oradb:/HR/TB_XML")//article let $cont := $book/bdy  where  $cont   [ora:contains(text(), "(near((The,power,Love),10, TRUE))") > 0] return $book
    ERROR:
    ORA-19279: XPTY0004 - XQuery dynamic type mismatch: expected singleton sequence
    - got multi-item sequence
    XQUERY for $book in  fn:collection("oradb:/HR/TB_XML")//article let $cont := $book/bdy  where  $cont   [ora:contains(., "(near((The,power,Love),10, TRUE))") > 0] return $book//bdy
    /*ERROR:
    ORA-01706: user function result value was too large
    Regards,
    Daiane

    below query works for 1 iteration . but for multiple sets i am getting following error .
    When you want to present repeating groups in relational format, you have to extract the sequence of items in the main XQuery expression.
    Each item is then passed to the COLUMNS clause to be further shredded into columns.
    This should work as expected :
    select x.*
    from abc t
       , xmltable(
           xmlnamespaces(
             default 'urn:swift:xsd:fin.970.2011'
           , 'urn:swift:xsd:mtmsg.2011' as "ns0"
         , '/ns0:FinMessage/ns0:Block4/Document/MT970/F61a/F61'
           passing t.col1
           columns F61ValueDate                Varchar(40) Path 'ValueDate'
                 , DebitCreditMark             Varchar(40) Path 'DebitCreditMark'
                 , Amount                      Varchar(40) Path 'Amount'
                 , TransactionType             Varchar(40) Path 'TransactionType'
                 , IdentificationCode          Varchar(40) Path 'IdentificationCode'                 
                 , ReferenceForTheAccountOwner Varchar(40) Path 'ReferenceForTheAccountOwner'
                 , SupplementaryDetails        Varchar(40) Path 'SupplementaryDetails'       
         ) x ;

  • How we can limit the number of concurrent calls to a WCF service without use the Singleton pattern or without do the change in BizTalk Configuration file?

    How can we send only one message to a WCF service at a time? How we can limit the number of concurrent calls to a WCF service without use the Singleton pattern or without do the change in BizTalk Configuration file? Can we do it by Host throttling?

    Hi Pawan,
    You need to use WCF-Custom adapter and add the ServiceThrottlingBehavior service behavior to a WCF-Custom Locations.
    ServiceThrottlingBehavior.MaxConcurrentCalls - Gets or sets a value that specifies the maximum number of messages actively processing across a ServiceHost. The MaxConcurrentCalls property specifies the maximum number of messages actively
    processing across a ServiceHost object. Each channel can have one pending message that does not count against the value of MaxConcurrentCalls until WCF begins to process it.
    Follow MSDN-
    http://msdn.microsoft.com/en-us/library/ee377035%28BTS.10%29.aspx
    http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicethrottlingbehavior.maxconcurrentcalls.aspx
    I hope this helps.
    Rachit
    If this answers your question please mark it accordingly. If this post is helpful, please vote as helpful by clicking the upward arrow mark next to my reply.

  • Synchronizing Creation of a Singleton Object

    I've encountered a synchronization issue I haven't seen covered in the material I've read so far. My server app uses message driven beans that maintain a variety of lookup tables (maps, actually), to do data validation. Each map is a singleton, and is created with lazy instantiation (i.e., not created until requested the first time). The problem is this: I want to prevent one thread from trying to read the map while another is creating it. Until the map is created, there's nothing to synchronize, but after it's created, there's no point in synchronizing either, because it will never change. The only time I need synchronization is during the one time the map is created. I don't want to synchronize later accesses to the map, for performance reasons. The code examples I've seen so far don't address this particular issue. Here's a code snippet of how I'm thinking of implementing this. Any comments or criticisms would be greatly appreciated.
    This code is from the the superclass of my data validation classes. The design is that a thread/bean needing map access would call getMapIfNeeded(), then do the lookup. The buildMap() method calls a separate, unsynchronized database class
    * Builds the lookup map if it doesn&rsquo;t already exist.
    * @param attribute Name of the attribute in table <span class="oracle">efm_accp_valu</span>.
    * @param map Map against which we&rsquo;ll validate values. If non-null, nothing is done.
    * @return The map (newly created if the input argument was <code>null</code>).
    * @throws APISystemException If a serious system error occurs.
    * @see #getListIfNeeded(String, List)
    protected static Map getMapIfNeeded(final String attribute, Map map)
       throws APISystemException
       if (map == null)
          map = buildMap(attribute);
       return map;
    * Builds the lookup map if it doesn&rsquo;t already exist.
    * @param attribute Name of the attribute in table <span class="oracle">efm_accp_valu</span>.
    * @param map Map against which we&rsquo;ll validate values. If non-null, nothing is done.
    * @return The map (newly created if the input argument was <code>null</code>).
    * @throws APISystemException If a serious system error occurs.
    * @see #getListIfNeeded(String, List)
    protected static synchronized Map buildMap(final String attribute)
       throws APISystemException
       return AcceptableValueDAO.getMap(attribute);
    {code}

    After doing some more research, I've concluded that, in my scenario at least, a better solution is to create the maps in static blocks. This avoids synchronization issues altogether, with the disadvantage being that if a database exception is thrown in the static block, I can't do much except print the stack trace. If anyone knows better, don't be shy about speaking up!

  • What is the best practice - singleton & components

    I am converting a Flex 3.5 project to 4.0 and have hit a few snags.  One issue that I'm not sure about is the way to address labels.  We switch between English and Spanish if you click a button.
    I decided to make the component's labels all based on a singleton class.  The label values there would alter between the languages.  I made them bindable in the singleton.
    1) should I directly associate the labels with the singleton "get" method for the appropriate label
    2) should I have a bindable variable in the component that is set from the singleton "get" method and then associate that variable with the various labels
    The first method saves a variable in the component while the second seems slightly more readable.
    Way one:
            [Bindable]
            protected var childSupLabel:String = getLabels.getExpChildSupLabel();
            <DHSclasses:AutoResizableTextArea
                  id="courtOrderedChildSupportLabel"
                  text="{childSupLabel}"
                  autoResize="true"
                  editable="false"
                  tabEnabled="false"
                  textAlign="right"
                  wordWrap="true"
                  left="5"
                  width="89%"/>
    Way two:
                    <DHSclasses:AutoResizableTextArea
                        id="elderlyMedicalExpensesLabel"
                        text="{getLabels.getExpMedExpLabel()}"
                        autoResize="true"
                        editable="false"
                        tabEnabled="false"
                        textAlign="right"
                        wordWrap="true"
                        left="5"
                        width="89%"/>

    Jerry,
    I keep asking for a simple test case.  It should only take an hour or so to create, much less time than you’ve spent and we’ve spent trying to guess how your code works from snippets.  There are two common approaches to creating such a test case.  One is to start from an empty app and copy in a few things at a time, another is to start with a copy of the current app and comment stuff out.  A test case is unambiguous.  I put it into the debugger and the problem will appear and we can make explicit recommendations.  Emails and code snippets are way to ambiguous.  Flex isn’t particularly hard, and the folks on the forum are quite helpful, but you have to help us help you by removing ambiguity.  I know the temptation is to hope that spending 30 seconds to send a snippet and question will save you from the hour of creating the test case, but the way I see it, there are several advantages to taking the hour to prepare the test case.  They are:
        -you might be waiting that hour for a response anyway,
        -in preparing the test case, a significant number of people discover the solution on their own, long before the hour is up
        -the chances you’ll get bad advice goes way down.
        -the inability to create a test case quickly serves as an indicator that your app is not modular enough
    I have touched many of the support issues you’ve logged via your support contract with Adobe.  Their process is also quite similar.  The support tech will ask for a simple test case.  By using the Adobe Support, you will get guaranteed, dedicated responses.  That’s what you’ve paid for.  Use it to your advantage.
    You are welcome to fire off the quick 30-second question, but when a responder asks for a test case, it is time to take the time to create one.  Also, you started your last reply by saying “I listen”, but Amy and I both have mentioned the Array event dispatching issue and I have asked for a test case several times.
    I will repeat a guess one more time as to the nature of this particular problem, which I described in an earlier response, then I will no longer respond to this thread until I see a simple test case posted.  And that is: The variable for the English class is not being initialized before it is being used.  When you step through in the debugger, all get functions in the class get called in order to populate the debugger’s variables pane, and that can cause initialization of values to occur in a different order than when you just run the app.  Variables with metadata are implemented as get functions so they can be affected.
    Adobe wants all of our customers to continue to use Flex.  Flex’s main advantage is reduced development costs.  The best way to show your management the advantages of Flex is the continue to improve your development practices to be more efficient, and that includes the development of modular code, use of existing features like the ResourceManager instead of trying to develop your own, and a refinement of the way you use resources like forums, the internet, and Adobe Support in getting your application ready for production.
    Going from Flex 3 to Flex 4 is a big change in development practices if you want to use the Spark components.  The principle behind Spark was to enable designers to control every aspect of the visuals without having to learn about ActionScript and CSS styles.  If that principle does not provide a significant advantage to you, then the MX components may make you happier.  Spark also provides a consistent skinning workflow.  If you don’t do much custom skinning because everything you need to change is available via CSS, then you also have less of a reason to use the Spark components. You can still move to Flex 4 and use the MX components and still get the advantages of two-way data binding, the new states syntax, and more.  Just use the MX components and specify the Halo theme, as I have suggested before.
    -Alex

  • Do I need to synchronize a singleton just for reads?

    Hello forum. Here's my situation: I keep config data for pages on my website in an XML file, I load said XML file in a startup servlet, creating a JDOM Document object, accessed by a singleton.
    Every time a page is loaded, the page accesses this Document object via the singleton, sees whether the page is secure, which template it should use, a bunch of stuff.
    Now, because the Document object is created when the context is started, and is never written too, only read, do I need to synchronize it?
    I read "Threading lightly, Part 1: Synchronization is not the enemy," on ibm.com (http://www-128.ibm.com/developerworks/java/library/j-threads1.html) in hopes of answering my own question, and the most relevant paragraph states:
    "If you are writing data that may be read later by another thread, or reading data that may have been written by another thread, then that data is shared, and you must synchronize when accessing it."
    But does my scenario fit? Yes I'm writing data that will be read by another thread, but no thead is accessing this data until the context is fully loaded and the object is fully instantiated. The object is not being written to by threads asynchronously... I just run the risk of it being read at the same time. Do I need to synchronize? If so... having synchronized variables in a servlet environment is bad, so what other approach should I take?
    Thanks for your help.

    But does my scenario fit? Yes I'm writing data that
    will be read by another thread, but no thead is
    accessing this data until the context is fully loaded
    and the object is fully instantiated. The object is
    not being written to by threads asynchronously.If all the writing is complete before any of the reading starts, then there's no need to synchronize the reading.
    .. I
    just run the risk of it being read at the same time.There's no risk in multiple concurrent reads.
    Do I need to synchronize? If so... having
    g synchronized variables in a servlet environment is
    bad, so what other approach should I take?Couple minor points:
    * You don't have synchronized variables. You have synchronized blocks and methods.
    * Using synchronization in a servlet context isn't in and of itself necessarily bad. Having multiple requests sync on the same lock can hurt response time, so try to avoid it, and if you must do it, keep the critical sections as small as possible.

  • What is the significance of Singleton Property?

    Hello guys!!!
    Can some one elobarate the significance of Singleton Property?
    Also, please suggest me a scenario, where we use Singleton Property.

    HI,
    click on ur node and on the singleton proprty click F1. u will get the full detail.
    The property "Singleton" specifies the number of instances that can exist in a dependent context node (that does not belong directly to the root node).
    If the property "Singleton" is set, exactly one instance of the node exists. Its content changes when the lead selection of the parent node changes.
    If the property "Singleton" is not set, one instance per parent instance exists. The content of the instances does not change when the lead selection of the parent changes.

  • Best Practice: passing properties to a Singleton

    Hi,
    I have an object in my app that must only exist once. It is a DatabasConnectionPool. I would like to implement it as a Singleton and access it from anywhere in the app with
    DatabaseConnectionPool dbcp = DatabaseConnectionPool.getInstance();
    But the thing is that I would like to pass it some settings: number of connections to the database, username and password, ...
    If I had a constructor for the class I would pass a Properties object with the constructor containig all the values but how do I do it with a Singleton?
    Right now I have:
    class Singleton {
    private static Properties _appProps = null;
    private static Singleton _instance = null;
    static public void setProperties(Properties appProps) {
    _appProps = appProps;
    static public Singleton getInstance() {
    if (null == _instance) {
    instance = new Singleton(appProps);
    private Singleton(Properties props) {
    So, the Launch code for the application reads the .properties files and calls:
    DatabaseConnectionPool.setProperties(props);
    WebServer.setProperties(props);
    LDAPServer.setProperties(props);
    Thanks a lot for your time guys!
    Rafa

    You don't need synchronization at all if you do it the way a previous post suggested:
    private static Singleton instance = new Singleton();
    public Singleton getInstance(){
        return instance;
    }This is lazy initialization by default because the singleton instance will only be created when the class is loaded into memory. It will be loaded into memory when you first call getInstance() so it's already using lazy initialization.
    The properties question seems to have several options
    1. Use your setProperties method to pass in dynamic properties. This will potentially make your singleton behave differently between uses if you change its properties while it's running.
    2. Hardcode the properties inside the singleton. This doesn't allow dynamic changes.
    3. Your connection pool is probably dishing out Connection objects and creating new ones when needed right? So, put the Connection creation in a different class called ConnectionFactory and pass in the factory to the singleton. This way you can customize the kind of connections to make in the factory without changing the singleton code. All the singleton cares about is saying factory.createConnection() and returning it.

  • Singleton

    I have written a classic Singleton which appears to work fine. One issue bothers me. I wish to collect error messages and return them to the caller rather than throw the error(s). I am concerned that given the single instance of this class, there could be -conflict- in generation of these error messages ....in other words, could caller1 get /see error messages from caller2 ....this code is running in a JAVA class as part of a JSP / Struts environment ....
    Rod .
    public class SingleClass {
    // Sample usage:
    // SingleClass.getInstance().setExceptionList();
    // X509Certificate cert = SingleClass.getInstance().getCACert ("xxx");
    // SingleClass.getInstance().getExceptionList();
    private SingleClass() {
    // Define our security provider
    Security.addProvider(new BouncyCastleProvider());
    * A handle to the unique instance.
    private static SingleClass _instance = null;
    // Errors Collection
    private ArrayList EXCEPTIONLIST;
    // Our cache of CA Certs
    private static HashMap cachedCerts = null;
    // How long are cache entries valid - 5 days default
    private static long cacheLife = 5 * 24 * 60 * 60 * 1000;
    public static void clearCache() {
    cachedCerts = null;
    public static SingleClass getInstance() {
    if ( _instance == null ) {
    _instance = new  SingleClass();
    return _instance;
    public ArrayList getExceptionList() {
    return EXCEPTIONLIST;
    public void setExceptionList() {
    EXCEPTIONLIST = new ArrayList();
    public X509Certificate getCACert(String caCertDN) {
    X509Certificate cert = null;
    if ( somecondition ) {
    // generate an error message
    EXCEPTIONLIST.add(msgParams);
    return cert;
    etc.

    could caller1 get /see error messages from caller2 Well yes. Thats the point of a singleton isn't it? There is only one instance, shared by all the callers. If you want each caller to store their own error messages, a singleton is not the way to do it.
    If you are using Struts, why are you not using the Messages/Errors functionality provided there?

  • Static VS Private constructor in singleton

    Dear All
    Can u tell me waht is the basic adiffernce B/w static methpd call and singleton pattern.
    Even in bothe the case we carete only one ibstance.

    For me, I like to use singleton when I need to
    perform some things inside the constructor. Butthere
    is other reason, more important: if one day youneed
    to modify to a "simple class patern", that is,
    with
    a
    simple constructor, this maintenance will be
    relativelly easy if you use singleton.And again, to me, none of this makes any sense.How
    is maintenance eased by placing code in a
    constructor? Why not in the static facade? Whynot
    in a static initializer? They are all equally'easy'
    IMO.
    suppose the following static method, that is using
    the static method of TheClass:
    public static void method() {
    TheClass.staticMethod();
    }Now you have to change, that is, the class now has to
    be a class with more than one instance, because of
    the change in the business rule of your system.
    Therefore, not only one instance anymore will be
    used. The maintenance of your system will be more
    complicated, doesn�t it? See below:
    private TheClass objClass;
    public static void method() {
    //ooops, it won�t compile
    objClass.staticMethod();
    }If you develop your system based on singleton
    pattern, you will be more prepared for this kind of
    maintenance.
    Of course, there are other solutions for this unlucky
    situation. Actually, this problem occur when you are
    developing a system, and the business rules are not
    so definitive yet, so changes in these rules are
    happening with a relative frequency. I am just saying
    a probably unlucky situation that might happen.I fail to see how you can do anything but alter the class and its dependencies if the requirements change. Is this not always the case? How does having a static method (or a Singleton) obviate the issue any more over any other type of class, or even switching between the types?
    How does making the object a Singleton 'prepare' me for change? In your mind, the dot-notation may be convenient over writing 'new', but other than that, I can't see how.
    - Saish

  • Hi! regarding the singleton property in webdynpro abap

    Hi experts ,
    Could anyone explain me in detail the property of singleton and wht r the conditions tht we should use wht will represents..
    plz explain me in detail......rather than sending links plz do explain me in detail....
    Regards,
    Sana...

    Cardinality : number of possible elements within the node.
    Singleton property means whether or not all instances of this node get created at runtime or not.
    Singleton property is mostly used to save memory & increase performance. we would go for singleton nodes in cases where UI needs only display from one-instance of data from my node.....
    What happens when you set singleton property to YES for a node??  Assume you have context structure like
    Context
         Vehicle( parent node )
           ( attribute veh-ID primary key for all types of vehicles, dealer, area )
              twowheeler( subnode of vehicle with cardinality-0..n singleton-NO)
                        ( attributes veh-ID, regno, model, color)
              fourwheeler( subnode of vehicle with cardinality-0..n singleton-YES)
                       ( attributes veh-ID, regno, model, color)
    At design time you fill the data within this context. Now you have 100 entries under the subnode  twowheeler & 90 entries under the subnode fourwheeler . You create UI elements to display the node twowheeler details in a View . At runtime when user selects the veh-ID and identifies that a twowheeler data needs to be fetched/displayed all the 100 entries for the twowheeler node get created in the background although you are displaying only the ONE corresponding to the veh-ID.
    if Veh-ID selected coresponded to fourwheeler( singleton property -yes) only ONE row of the data from the fourwheeler entries would have been fetched and ONLY Once instance of the fourwheeler would be created by background process!!
    thus saving memory & processing time.
    Scenarios singleton-YES
    If i were required to display details of only ONE vehicle based on the entered Veh-ID , i will make twowheeler & fourwheeler nodes singleton-YES.
    Scenario singleton-NO
    if i were required to show all the vehicles that belong to one particular Area.

Maybe you are looking for