Things to consider while making a class singleton?

sometimes i need to share the state of object across application.I get confused should i declare it singleton or declare state vaiables as static.
As per mythoughts, if intention is just to share the state of object across application i should go for static variables. Is this right?
My understanding about when we should go about singleton is below
We should declare the class as singleton when we need only one instance across jvm. But i am not unable to find any practical scenario
when we where we may need singleton . Any help here will be appreciated. Everywhere on different sites i get to see the example of logger
class where the reason is generally given as so that single log file is created not multiple log files.
But again this could have been achieved with declaring the file variable as static in logger file?
So actual reason is for declaring the logger as singleton is becuase we need the single log file with issues avoiding concurrent writing
which wont be possible if we make the separate instance of logger for each write..
Is the above reasoning correct so that i can proceed in right direction?

How will declaring its state as static accomplish that objective?With declaring variables as class variable instead of instance variables, there will be a single copy of each variable. In each instance (in this case logger if we dont declare it singleton) we can check if file is already created or not. I mean it will be visible across all instances.
No, because the file name isn't the only state. There is also the output stream/writer, its current position, its charset, the log level, the logger name, its filters, its formatters, ...Agreed. I just wanted to convey the point. As you said there will be other parameters,in that case we can declare all of them as static.
A configuration file holder is a good example: there is only one configuration file so there should only be one holder instance.Thanks for pointing it out. Configuration file is used mainly to read the properties. we usually dont update the values there.So even if we dont make it singleton it may be correct. The advantage i can think of making it singleton is that if configuration file is used frequently then we dont have create the object again and again.
So actual reason is for declaring the logger as singleton is becuase we need the single log file with issues avoiding concurrent writing
No it isn't, and that doesn't follow from anything you said previously so the 'so' part is meaningless.I want to say here is that t to have single log file should not be the only reason behind making the logger file as singleton, other reasons can be handling of concurrent writing too.
Have a look at the Wikipedia article on the Singleton pattern, or buy the booki have gone through the singleton pattern in headfirst book and some of the articles on net. But they mainly describe how the make the class as singleton and the reason that We should declare the class as singleton when we need only one instance. But looking for actual scenarios where we need singleton. So i took the examplle of logger file which is used in many project and trying to understand it is constructed as singleton so that i can use in my project if required.
Edited by: JavaFunda on Aug 28, 2011 3:51 AM
Edited by: JavaFunda on Aug 28, 2011 3:56 AM

Similar Messages

  • Things to consider while Creating Indexes in the tables

    Hi All,
    We have some application slow issues becasue of the tables which it is calling are Heap. There are Primary keys created on few tables though. I have to think and design the indexing on those tables. What are different things need to check to design the Indexes?
    Thanks
    Swapna

    Hi All,
    We have some application slow issues becasue of the tables which it is calling are Heap. There are Primary keys created on few tables though. I have to think and design the indexing on those tables. What are different things need to check to design the Indexes?
    Thanks
    Swapna
    Adding to what others have said create an index and check execution plan whether it is being used by optimizer or not if it is used and query runs fast that index can be kept
    You should also take help of DMV
    sys.dm_index_usage_stats to see whether index is being utilized or not. refer to user seek user update and user scan col. If Update is very much greater that seek/scan index is probably not utilized , you can consider removing it
    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it.
    My TechNet Wiki Articles

  • Things to consider while uploading the photo to show up in ESS

    Hello All,
    We are planning to have Employee Photo in ESS, We just want to know what all things need to be considered, like
    1) Database size
    2) constraint on size.(how to restrict the size of the image)
    3) We will be doing the configuration required for that.
    other than these what things have to be considered.
    Please help me out in this.
    Points will be awarded for the appropriate answers.
    Pramod

    Solved

  • Things to consider while designing an interface

    Hi friends,
    I've got an opportunity to design (functional design) the first outbound interface of my career. I'm little confused with the data mapping part of it with the legacy team. I want to follow a structured method to avoid missing out things and bother the legacy team again and again with silly question. Can anyone provide me a structured method and the important things that I should know and discuss with the legacy team?
    I'm new to SDN and I'm not aware of all the protocols of the forum. Please excuse me if I've put accross a wrong question.
    Thanks,
    Rohit

    Hi,
    When you working on design what kind of design??
    Like have you got functional requirements from functional Team?? or you involving in gathering functional Requirement??
    Functional Design:
    Nothing to do with your Interface design, try to understand the business requirement, and identify the source data and target data, and what system is going to be source and target.
    then identify the is there any business data validations and data mapping between source and data, for this you have maintain one excel sheet for data mapping, define source and target structures and business logic involved in mapping.
    in this phase you have to develop functional document, which gives the high-level business requirement and graphical representation of data flow between source and target system(MSVisio diagram).
    Technical Design:
    Technical design will talk about how youu2019re going to achieve your functional requirement using PI.
    First analyze the requirement, like source and target systems and which adapters will full fill your requirement to retrieve/send data to source/target systems.
    Then identify which type of interface it is Synchronous or asynchronous.
    Then you have to identify mapping logic, refer functional data mapping document and identify which mapping will be required(Message ,JAVA,XSLT and ABAP ),if your requirement can be achieved using message mapping then well and good.
    Identify the best approach to implement your business requirement using SAP PI, prepare design document, if you donu2019t have much experience in SAP PI, then refer senior recourse about design, he will help you if anything needed to be changed in your design approach.
    Now you are clear with requirement, mapping logic and ready with design.
    Start development refer naming convention document before starting your requirement and follow the valid naming standards and complete your development and mean time complete technical specification document for your interface.
    Regards,
    Raj

  • Things to consider while copying a seeded package.procedure?

    Hi,
    I was trying to do some customization as part of my project in PO_APPROVALLIST_S1.rebuild_approval_list. I copied the procedure and put it in my package after renaming it and done some code changes. The syntax errors were corrected and the package got compiled successfully.
    But when I did testing in Requisition Approval -Forward Action where I customized, the workflow is erroring out in Exception. Retry also not working.It is again going to exception
    Failed Activity: Update Approval List Response
    Activity Type: Function
    Error Name: -6512
    Error Message: ORA-06512: at line
    Error Stack : Wf_Engine_Util.Function_Call(PO_APPROVAL_LIST_WF1S.UPDATE_APP_LIST_RESP_SUCCESS, REQAPPRV, 23371461-562932, 968804, RUN)
    How can i identify at which point it errs out? Is there any problem if we are using seeded procedures in custom packages?
    Please help me to proceed further..
    thanks,
    Nish

    Hi, since you've modified a package that is tied to the workflow, it would be a good idea to stop/restart workflows because original code is probably in memory and your modification are not considered but the state has changed.

  • Things to consider while merging two DBs?

    Dear gurus,
    We have 2 instances, 1 is prod and other is replica of prod, just 4-5 hours behind prod,
    used for queries just to reduce overhead on PROD,(the second instance is not a DSS/warehosuese/OLAP env it is just replica on instance 1) with some additional indexes,
    now the management has decided to remove the second instance,
    my question is : how do i proceed that the queries running on instance 2 should not create any problem when shifted to instance 1
    thanks

    user548749 wrote:
    my question is : how do i proceed that the queries running on instance 2 should not create any problem when shifted to instance 1If an existing query on instance 2 uses an index which is not available on instance 1, there can be a hefty performance impact. Or instance 1 can already be quite busy and unable to handle the additional volume of queries from instance 2. Or the buffer cache on instance 1 may not allow the same level of caching enjoyed by queries on instance 2 (due to production processes that are absent from instance 2).
    So there is no simple way to identify problematic queries that worked fine on instance 2 and would be a problem on instance 1. For starters, you will need to parse every single query on both and compare the resulting execution plans simply to determine if there will be a difference.
    Also, as instance 1 contains more data than instance 2 (which lags some hours behind), execution plans can quite likely be different in some cases due to the volume of data.
    This is not a simple exercise to undertake. There will be execution plan differences - and the difference may not be a bad thing due to the differences of instance 1 compared with instance 2.
    What you can do is implement resource profiles on instance 1 for instance 2 queries - and that way attempt to control those queries resource utilisation and thus minimise their impact on instance 1.
    Bottom line though - I see this as a lot of manual and hard work to make the replacement of instance 2 with instance 1 a transparent one to the end users that are using instance 2 for queries.
    Billy

  • I m facing challenges while connecting to wi fi , i bought my 5s in dubai , however this is a verizon carrier activated device , so i m not getting support from apple uae, plz suggest , i bought 5s to simplify things and ended up making things very comple

    I m facing challenges while connecting to wi fi , i bought my 5s in dubai , however this is a verizon carrier activated device from US , so i m not getting support from apple uae, plz suggest , i bought 5s to simplify things and ended up making things very complex

    You have not replied in full.
    Check here warranty status https://selfsolve.apple.com/agreementWarrantyDynamic.do
    Check here for Hardware troubleshooting.
    Regarding warranty and out-of-warranty services you already have answer. Verizon will help only if they sold the iPhone.
    Incidentally in UAE
    Technical support for iPhone in this region is provided by the carrier, not Apple.
    So, Contact DU.
    Best

  • Error while making connection with remote oracle database

    Dear,
    I am trying to make connection with oracle database but when i run java file it's raise an error "classnotfoundexception oracle.jdbc.driver.oracledriver"
    DriverManager.getConnection(
      "jdbc:oracle:thin:@erp:1521:ORCL", "apps",
      "apps");
    Pls any body have idea.
    Thanks.

    Thanks for support.
    Below is error which i am getting while making connection with remote database.
    C:\Program Files\Java\jdk1.7.0_05\bin>java OracleJDBC
    -------- Oracle JDBC Connection Testing ------
    Where is your Oracle JDBC Driver?
    java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
            at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
            at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
            at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
            at java.lang.Class.forName0(Native Method)
            at java.lang.Class.forName(Class.java:186)
            at OracleJDBC.main(OracleJDBC.java:13)
    Advice.

  • Error While Creating Asset Class

    Hi Friends,
    I am getting the following error in development client while creating the asset class AB2200.
    "Screen Layout 200 was not created"  but the same was created.
    Please guide me how to handle this error and the reason for me getting this error message while creating asset class.
    Your quick response would be highly solicited.
    Thanks and Regards,
    C.R.Srinath

    Hi Srinath
    There are 2 things.. Create the screen layout and Define the screen layout... (IMG> AA > Master Data> Screen Layout for asset classes)
    Complete both the steps here and specify the same sccreen layout in your asset class
    Regards
    Ajay M

  • How to reflect a new field in Bank data while making payment through F-53?

    Hello Experts,
    How can i reflect a new field (payment reference) in bank data while making payment through F-53?
    I have tried to do it by Field status group(OBC4) but the same is replicating in vendor invoice but not in vendor payment.
    I tried it at both level,fsg anf posting key,But no use.
    Is there any other process to make available and required field in BANK DATA of vendor payment?
    Please suggest .
    Regards,
    Sumeya offrin

    Hello Sumeya,
    Please consider note 145864 which explains what you have to do to
    make this field visible in your selection criteria:
    "In Transaction FB00 (Financial Accounting Editing Options -> Open items
    activate the flag 'Payment reference as selection criterion'.
    This is valid for incoming payment; please test if the same procedure
    is valid for outgoing payment as well.
    I  check the  issue, and unfortunately these function seems to not be supported for vendor open items.
    When you try to select the 'Payment Reference' in Additional selections
    the following messages is arised:
    'No account specified, items selected via document no. or reference'
    That means,when you do not specify an account in F-53 you can only
    via Reference and/or document. This is not a bug but system design.
    For additional reference you can check the note 451105.
    The note made clear that the specification of an account is required for vendors during the selection via payment
    reference.
    Kind Regards,
    Fernando Evangelista

  • Need help making this class Runnable.

    Hello,
    This class (see below) is working fine the way it is but I have a little problem, I need to execute aprox 500+ commands and each command takes between 30sec to 3 minutes to complete which translate into hours for the job to finish.
    I want to speed the process by multi-tasking and executing (possibly) all commands simultaniously by somehow making this class Threaded/Runnable (miltitasking). There must be something tricky about Runtime class and cannot figured it out.
    Your help would be highly appreciated.
    Regards,
    Ulises
    public class CmdTest {     
    public static void main(String[] args) throws java.io.IOException {
    String outFile = "./ds8300/lsvogrp.txt";
    PrintWriter bout = null;
    try {
    bout     = new PrintWriter(                         new FileWriter(new File(outFile)));     
    } catch (IOException e) {
         e.printStackTrace();
    Runtime run = Runtime.getRuntime();
    run.traceMethodCalls(true);
    Process proc2 = run.exec("cmd /c dscli -user user -passwd psw" + "lsvolgrp -l");
    BufferedWriter ot = new BufferedWriter(
    new OutputStreamWriter(proc2.getOutputStream()));
    BufferedReader br = new BufferedReader(
    new InputStreamReader(proc2.getInputStream()));
    BufferedReader er = new BufferedReader(
    new InputStreamReader(proc2.getErrorStream()));
    try {
    String s;
    while((s=br.readLine())!=null) {
         System.out.println(""+s);
         bout.println(s);
    while((s=er.readLine())!=null) System.out.println("ERR:"+s);
    bout.close();
    System.exit(0);
    }catch (Exception ie) { //catch (InterruptedException ie) {
    System.out.println("Interrupted:"+ie.getMessage());}
    }

    Seems like the same question you asked last year.
    http://forum.java.sun.com/thread.jspa?threadID=5181153&messageID=9705196#9705196
    The proper way to design software is to start at the beginning and design Classes. Not try to butcher that which is working.
    You're running work outside the JVM and this work might interfere with other, similar work (the multi-threading issue.)
    I'd start with paper and pencil and see what conflicts might arise.

  • Can you add different songs to different slides while making a slideshow

    Can I change music on individual slides while making a slideshows

    You mean javascript, right? That's not Java.
    You cannot apply such things to a table.
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.dreamweavermx-templates.com
    - Template Triage!
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    http://www.macromedia.com/support/search/
    - Macromedia (MM) Technotes
    ==================
    "nyran20" <[email protected]> wrote in
    message
    news:ek33hv$g3k$[email protected]..
    > Hi all. Can someone tell me if you can add different
    states to an html
    > table?
    > I am using a table as a nav bar now, but I want to make
    it more fun by
    > adding
    > an over state. I feel that FW doesn't offer some of the
    simplicities that
    > a
    > regular HTML table does. I have the states (in java)
    made in FW, how do I
    > apply them to my existing html table?
    >

  • J2EE JTA-00115 An exception occurred while making afterCompletion notificat

    Hi
    we are trying to use declarative transaction management feature of spring framework. For this we are using TopLinkTransactionManager but we ere getting following error.
    ---error---
    Could not open TopLink Session for transaction; nested exception is
    java.lang.UnsupportedOperationException: SingleSessionFactory does not
    support managed client Sessions
    we gix this by changin sessions.xml file
    from
    <session xsi:type="database-session">
    to
    <session xsi:type="server-session">
    now getting thiss exception
    2007-08-23 10:00:40.446 WARNING J2EE JTA-00115 An exception occurred while making afterCompletion notifications:
    Exception Description: UnitOfWork [UnitOfWork(
    null
    Oracle10Platform)] was rendered inactive before associated externally managed transaction was complete.
    Can anyone please give some idea how to fix it. Thank you very much.
    Following is transaction configuration in our application context file.
    <bean name="sessionFactory"
    class="org.springframework.orm.toplink.LocalSessio nFactoryBean">
    <property name="configLocation" value="sessions.xml"/>
    <property name="sessionLog">
    <bean
    class="org.springframework.orm.toplink.support.Com monsLoggingSessionLog"
    />
    </property>
    <property name="dataSource" ref="dataSource"/>
    </bean>
    <bean id="txManager"
    class="org.springframework.orm.toplink.TopLinkTran sactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <aop:advisor/> bean below) -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
    <!-- the transactional semantics... -->
    <tx:attributes>
    <!-- all methods starting with 'get' are read-only -->
    <tx:method name="get*" read-only="true"/>
    <tx:method name="load*" read-only="true"/>
    <!-- other methods use the default transaction settings
    (see below) -->
    <tx:method name="*" rollback-for="BusinessException"/>
    </tx:attributes>
    </tx:advice>
    <!-- ensure that the above transactional advice runs for any execution
    of an operation defined by the FooService interface -->
    <aop:config>
    <aopointcut id="serviceOperation" expression="execution(*
    ie.vhi.ias.app.service.*ServiceIF.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation"/>
    </aop:config>
    Here is our session.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <toplink-sessions version="10g Release 3 (10.1.3.1.0)" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <session xsi:type="server-session">
    <name>Session</name>
    <server-platform xsi:type="oc4j-1013-platform"/>
    <event-listener-classes/>
    <primary-project xsi:type="xml">ToplinkWorkbench.xml</primary-project>
    <login xsi:type="database-login">
    <platform-class>oracle.toplink.platform.database.oracle.Orac le10Platform</platform-class>
    <external-connection-pooling>true</external-connection-pooling>
    <external-transaction-controller>true</external-transaction-controller>
    <datasource>jdbc/TestDS</datasource>
    </login>
    </session>
    </toplink-sessions>

    Could you please run your application again, enabling the logging of the SQL statements. To enable, add the following to domain.xml:
    <log-service alarms="false" file="${com.sun.aas.instanceRoot}/logs/server.log" log-rotation-limit-in-bytes="2000000" log-rotation-timelimit-in-minutes="0" log-to-console="false" retain-error-statistics-for-hours="5" use-system-logging="false">
    <module-log-levels admin="INFO" classloader="INFO" cmp="INFO" cmp-container="INFO" configuration="INFO" connector="INFO" corba="INFO" deployment="INFO" ejb-container="INFO" group-management-service="INFO" javamail="INFO" jaxr="INFO" jaxrpc="INFO" jdo="INFO" jms="INFO" jta="INFO" jts="INFO" management-event="INFO" mdb-container="INFO" naming="INFO" node-agent="INFO" resource-adapter="INFO" root="INFO" saaj="INFO" security="INFO" self-management="INFO" server="INFO" synchronization="INFO" util="INFO" verifier="INFO" web-container="INFO">
    <property name="javax.enterprise.resource.jdo.sqlstore.sql" value="FINEST"/>
    </module-log-levels>
    </log-service>

  • Fixing the loupe tool position while making adjustments

    I haven't found a way to do this - maybe it's an enhancement - but just in case ....
    Is there a way to fix the loupe in position while making adjustments (ex. noise and sharpness)? I'd like the loupe to display real-time the results of the adjustments being made.
    I checked the manual but didn't see anything. Is it do-able or is it future?
    Thank you.

    I haven't found a way to do this - maybe it's an
    enhancement - but just in case ....
    Is there a way to fix the loupe in position while
    making adjustments (ex. noise and sharpness)? I'd
    like the loupe to display real-time the results of
    the adjustments being made.
    I checked the manual but didn't see anything. Is it
    do-able or is it future?
    Actually right around the time of 1.0.1 a number of people were asking for this - I also submitted a suggestion to see it as well.
    Currently the closest thing you have is to zoom in on a specific area at 100% and evaluate that region while making changes. That works pretty well, but with larger images 100% is not quite close enough.
    There are two ways to fix that I think, allow the user to define what the "100%' zoom really is, or allow the user to have multiple sticky loupes they could leave on an image.

  • Problem with audio while making a call

    I have a model 9810,
    I can hear no audio while making a call at all, however, while making the call if I press the speaker tab I can hear (as like a hands free made)
    I do not use a head set or in car kit, I just use it as a handset.
    All other audio is OK, I can hear the alerts as a call or text comes in, but as soon as I answer the call and place it near my ear I hear nothing
    Can someone please help 
    Thank you

    Hello,
    Questionz wrote:
    I am having the exact same problem, I am not sure why, but my ear speaker is not working. I tried resetting, removing the battery, but nothing seems to be working.. Putting the call on speaker works, bluetooth works, only my ear speaker is not working.
    I recommend that you attempt to boot into Safe Mode:
    KB17877 How to start a BlackBerry smartphone in Safe Mode
    It may take you multiple attempts to get the ESC key sequence (press/release/hold) correct, so be patient. When successfully into Safe Mode, see what happens.
    If the behavior ceases, then think carefully...what happened just before this behavior started? A new app? An update? A Theme? Something else? Think carefully as the smallest change could be causal...and attempt to undo whatever that was.
    But if the behavior continues in Safe Mode, then you may need to consider more drastic actions -- WIPE, OS Reload, BBSAK Wipe/Reload, and the "Bare Bones" OS Reload Process. To prepare, you should be sure that you have a full backup to your PC...please review the Backup link in my auto-sig on this post for instructions.
    You may also need the use of these tricks:
    KB10144 How to force the detection of the BlackBerry smartphone using Application Loader
    KB27956 How to recover a BlackBerry smartphone from any state
    http://crackberry.com/blackberry-101-lecture-12-how-reload-operating-system-nuked-blackberry
    Questionz wrote:
    I bought this from Blackberry store, is there any way I can give this in as warranty?
    When you purchased, you should have received information as to how to seek support, warranty or otherwise.
    Good luck!
    Occam's Razor nearly always applies when troubleshooting technology issues!
    If anyone has been helpful to you, please show your appreciation by clicking the button inside of their post. Please click here and read, along with the threads to which it links, for helpful information to guide you as you proceed. I always recommend that you treat your BlackBerry like any other computing device, including using a regular backup schedule...click here for an article with instructions.
    Join our BBM Channels
    BSCF General Channel
    PIN: C0001B7B4   Display/Scan Bar Code
    Knowledge Base Updates
    PIN: C0005A9AA   Display/Scan Bar Code

Maybe you are looking for

  • SmartForms - Is there a way to put PDF attachment in the body of Email?

    Hello All, Currently I have a Smart Form that generates an MAIL with a PDF attachment.  It works very nicely with from, to, and subject information correct.  A new request from the users is to show in the PDF output in the email vs. an attachment.  T

  • ITunes settings lost after reboot

    I have a problem where after a reboot the settings of iTunes are back to default. For example: it loses the account for the Store (I have to re-enter email address and password); it loses the wifi sync settings for my devices it shows the iTunes tuto

  • Multi-user login screen help

    I am looking into an application front end with NI hardware controlling a temp process. The fun thing is the multi-user login that controls the screens you can access. Does anyone know of a good way to accomplish this?

  • Siri is not responding to any question

    Siri is not responding.  latest 8.1.2 iOS.  I have started and restarted many times.  Any question whatsoever is met with the same response "sorry, i can't find that right now, please try again."   ANY question - what time is it, what is the temperat

  • Firefox4 is not displaying like when i first downloaded it

    when i first downloaded firefox 4 it was a whole lot different looking than firefox 3, i had full screen option under file menu and the file menu had all the regular options when opened, and my persona is not being displayed. my firefox4 keeps being