Just a SINGLE instance of a class

Hai !!!
Kindly take a look at the psuedocode below and tell me if this would create just a "single" instance of class A through out my application.
I have 3 classes A, B, C.
class B {
  private A a1 = null;
  public C method1 () {
    getA();
    //System.out.println (a1.toString());
    return new C(a1);
  private A getA() {
    if (a1 == null) a1 = new A();
    return a1;
} // end class BI used "System.out.println" to check if I got the same instance of class A. Is this correct?
Note: I got the same a1.toString() printed for different clients. Is this the way to check?
Thanks

Thanks to all of you. I am new to this kind of
programming. So having some difficulties.
In my program, no matter what, only one instance of
'B' is going to be used. It's like this: B b = new
B(); and this 'b' is used throughout. Or I can say 'b'
is a server object and all clients are going to look
up to only one 'b'. So is it enough to have just this
line of code inside the constructor of B : a1 = new
A();
Since there's going to be just one 'b', can I assume
there's going to be only "one" a1??
I feel I needn't even go into getData().
public class B {
A a1;
public B() {
a1 = new A();
public C method1() {
return new C(a1);
}The clients would be using 'b'(a single instance of B)
to access method1. So all the clients are going to get
the same a1. Am I right?
Thanks again !!!True, unless someone desides to use your code and makes a second B, or you do some manipulation later on and you end up making a new B. Then there are two As floating around and two Bs floating around, and you may not know it till some strange behavior occurs...

Similar Messages

  • How do i create a single instance of a class inside a servlet ?

    how do i create a single instance of a class inside a servlet ?
    public void doGet(HttpServletRequest request,HttpServletResponseresponse) throws ServletException, IOException {
    // call a class here. this class should create only single instance, //though we know servlet are multithreaded. if, at any time 10 user comes //and access this servlet still there would one and only one instance of //that class.
    How do i make my class ? class is supposed to write some info to text file.

    i have a class MyClass. this class creates a thread.
    i just want to run MyClass only once in my servlet. i am afriad, if there are 10 users access this servlet ,then 10 Myclass instance wouldbe created. i just want to avoid this. i want to make only one instance of this class.
    How do i do ?
    they have this code in the link you provided.
    public class SingletonObject
      private SingletonObject()
        // no code req'd
      public static SingletonObject getSingletonObject()
        if (ref == null)
            // it's ok, we can call this constructor
            ref = new SingletonObject();          
        return ref;
      public Object clone()
         throws CloneNotSupportedException
        throw new CloneNotSupportedException();
        // that'll teach 'em
      private static SingletonObject ref;
    }i see, they are using clone !, i dont need this. do i ? shouldi delete that method ?
    where do i put my thread's run method in this snippet ?

  • Managing Multiple threads accessing  a single instance of a class

    Hi,
    i have to redesign a class, say X, in such a way that i manage multiple threads accessing a single instance of the class, we cannot create multiple instances of X. The class looks like this:
    Class X{
    boolean isACalled=false;
    boolean isInitCalled=false;
    boolean isBCalled=false;
    A(){
    isACalled=true;
    Init(){
    if(!isACalled)
    A();
    B();
    C();
    isInitCalled=true;
    B(){
    if(!isACalled)
    A();
    isBCalled=true;
    C(){
    if(!isACalled)
    A();
    if(!isBCalled)
    B();
    }//end of class
    Init is the method that would be invoked on the single instance of this class.
    Now i cannot keep the flags as instance variables coz different threads would have differrent status of these flags at the same time, hence i can make them local, but if i make them local to one method, the others won't be able to check their status, so the only solution i can think of is to place all the flags in a hashtable local to method INIT AND INITIALIZE ALL OF them to false, as init would call other methods, it would pass the hashtable reference as an additional parameter, the methods would set the flags in the hashtable and it would be reflectecd in the original hashtable, and so all the methods can have access to the hashtable of flags and can perform their respective checks and setting of flags.
    This all would be local to one thread, so there's no question of flags of one thread mixin with the flags of some other thread.
    My question is :
    Is this the best way, would this work?
    In java, everything is pass by value, but if i pass the hashtable reference, would the changes made inside the called method to the hashtable key-value would be visible in the original hashtable declared inside the calling method of which the hashtable is local variable?

    In Java object variables are passed "by copy of reference", and primitive variables "by value".
    The solution with HashMap/Hashtable you suggest is ok, but I think you should read about ThreadLocal class:
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html

  • I want to run single instance of my class ?

    i have a class with name Abc, i want when my Abc class is
    in running mode then i cant run my Abc class again untill my
    Abc class not exit.
    i want to do that in pure java, i have one logic but it is not
    proper salution.
    my logic is that when my programe is start first check a temprery file
    which is created by my programe and when i want to exit then i delete
    that temprery file.
    but if computer is shutdown unproperly and my programe is in running mode then my file is not delete.
    please any body give me help.
    i m thanksfull.
    Arif.

    Hi,
    let's make it more precise as so "if my class is in running mode" is not very precise - I guess, you are not talking of a class which has implemented the Runnable interface and is executed via "new Thread(Abc).start()". I think, you want a class, which can only have one instance of it at a time, right?
    It is no problem, to make a class, which has only one instance - it is called a Singleton class - it consists of the following:
    public class MySingleton extends Object // or any other class
    public static final instance = new MySingleton();
    //the trick here is to declare its constructor private
    private MySingleton() { super(); }
    // some other methods here
    }There is only one instance of this class accessible via MySingleton.instance. The problem with it is, that it doesn't match your requirements, as so you are not able to instantiate this class ever again, even so you would declare the "instance" field not final and set it to null.
    What you can do now is dealing with security managers - check the documentation of the newInstance() method of the Class class and the SecurityManager class, there you will find several links to documentation related with the use of an security manager.
    greetings Marsian
    P.S.: all these *** in the text are the letters a s s :(

  • Auto-populate of SHELL_shellName_shell Upper form DE only functions in one single-instance project shell.  The DE in the BP Upper Form needs to auto-populate in two separate single-instance shells.  How can I get this DE to autopopulate in both?

      The Unifier environment
    contains two single-instance project shells, INF and PBS, and two multiple-instance child project shells, INFS and
    PB.    There is a single instance, non-workflow
    business process, ‘Project Information’ that contains a data element in the
    upper form definition, Project ID.  The Project ID is set to auto-populate from the multi-instance “INFS”
    project shell attribute, which is populated manually. 
    Issue:  The auto-populate functionality for the
    Project ID ‘Shell_shellName_shell’ data element within the single-instance
    Project Information BP only functions within one of the shells, either
    INFS or PB, but not both.  The INF and INFS shells are currently deployed
    to production, PB and PBS shell are not.
    It is critical that Project ID ‘Shell_shellname_shell’ data element is populated correctly in the
    Project Information upper form of both shells, INFS and PB,
    because that data element is referenced by multiple business processes and
    integrations. 
    The attribute form definitions for both single and multiple instance project shells are identical.  The Project ID utilizes the same data
    element ‘SHELL_shellName_shell’ as is defined in both shell attribute forms
    (INFS and PB). 
    The data definition source is a Unifier system-level variable, SYS Shell
    Name (String, 128, Text Box)
    Potential Solutions:
    1. Create a Project ID DE of another data type which can
    be successfully auto-populated from either shell.  Drawback: all BPs and integrations which
    reference Shell_Shellname_shell will need to be rewritten.
    2. Investigate converting the Project Information single-instance
    to a  multi-instance BP, and create a
    separate instance for each single-instance shell type.  Same Drawback as Option #1, but with additional
    rework.  Most likely Project Information
    would have to be recreated as a new BP.
    Not sure that this option would even work.
    3. Create a separate Project Information BP for PB.  Drawback:  Two separate BPs for Project Information would
    need to be created.  All existing BPs
    refer to Project Information, so this option could potentially invalidate the
    ability to use the existing BPs in the PB shell.

    Was it really necessary to post the whole API description?!?
    Locale[] locales = Locale.ENGLISH();ENGLISH is not a method in class Locale, so do not add the braces "( );".
    Also, the constant ENGLISH is not an array, but just a single Locale object.
    You didn't say what your problem was. What do you want to achieve with your program and what is it that you don't understand?

  • Seperate instances of server class for authentication

    I'd like to implement some form of authentication in my server class. I thought about adding a few login routines and while the client hasn't authenticated itself all calls to functions other than the login stuff will throw Exceptions.
    However, as I understand from the (in my opinion chaotic documentation and tutorial) every UnicastRemoteObject class is instanced only once and after that every client will use a threaded version of that same class instance... This would mean that if one client logs in, all clients log in as the object doesn't distinguise between clients.
    So I either need a way to instance the server class for every client or (perhaps even more graceful) use a Login class that spawns a server class as soon as the login has been accepted.
    Unfortunately I can't find anything on the web or the forums about this (lotsa problems like mine but either unanswered or different enough to be less than helpful).

    I'd like to implement some form of authentication in
    my server class. I thought about adding a few login
    routines and while the client hasn't authenticated
    itself all calls to functions other than the login
    stuff will throw Exceptions.
    However, as I understand from the (in my opinion
    chaotic documentation and tutorial) every
    UnicastRemoteObject class is instanced only once and
    after that every client will use a threaded version
    of that same class instance.No, you can have as many instances as you like but you have to start with a single object which is bound into the Registry. What you are after is a Session pattern like this:
    public interface Login extends Remote
      Session login(String credentials) throws RemoteException;
    public interface Session extends Remote
    /// ... whatever you want
    then a singleton instance of LoginImpl is bound to the registry, the client retrieves it, tries to get a Session by logging in. The implementation of login() just looks like this:
    public Session login(String credentials) throws RemoteException
    // check credentials, RemoteServer.getClientHost() &c:
    if not acceptable throw new AccessException();
    // otherwise
    return new SessionImpl(credientials);
    }Easy as pie.

  • How to synchronize a method for all instances of a class

    Hi,
    How to make a method synchronized for all instances of a class? If a simple method is synchronized, then multiple threads cannot access it at the same time. If we make the method as static, then we are making it synchronized at class level.How to make a synchronized method so that no two instances (objects) of a class can access it at the same?
    Thanks
    Neha

    Neha_Khands wrote:
    There is nothing wrong with that. Actually this question was asked in an interview. They didnt want to create a static method. They told me that synchronization can be achieved at instance level also. and for that we have to call some Class.getInstance().synchronied method inside constructor. Kind of a dumb question. First, synchronization does not occur "at a class level" or "at an instance level." Syncing is always the same--a single object's lock is obtained, which prevents any other threads from obtaining that lock. The only thing that makes it appear that there are special cases is that declaring a method synchronized obtains the lock associated with the instance or with the Class object for that class. But that's just syntactic sugar. The Class object lock is identical to the instance lock, which in turn is identical to a lock on some other arbitrary Object created just to serve as a lock. There's no such things as "locking the class" or "locking the instance."
    Second, and more important, making an instance method synced across all instances is a grotesquely artificial situation, IMHO, and if it were to ever come up, the right way to do it is to have that instance method call a static synchronized method.

  • Instantiate an instance inside its class

    I always read codes like following:
    Class A {
    A a = new A( );
    Could anybody tell me why a class is able to instantiate its instance inside itself.
    Another example:
    Class A {
    B b = new B( );
    Class B{
    A a = new A( )
    When Class A is running, it calls Class B, but when Class B is instantiated
    , it needs to call Class A. I am always puzzled about this kind of codes.

    Everything in the world is an object - not only the building, but also the blueprint for this building is some kind of sheet of paper.
    In Java, the Class Objects are loaded as soon as you go into runtime. The VM recognizes all necessary classes, and creates one single instance of them. So, static attributes are indeed a singleton pattern on class level...
    A class even has an own constructor. This constructor looks like this:
    class ClassA{
          // Insert Class Constructor input here
    }All static attributes are implicitly constructed in this class constructor.
    However, what you have written, is just a simple Form of:
    class ClassA{
       ClassA a;
       public ClassA(){
         a = new ClassA();
    }This is indeed a neverending loop, so this doesn't make sense. But it isn't unusual to hold a reference to another object of the same type.

  • Create multiple instances of same class but with unique names

    Hi,
    I'm creating an IM application in Java.
    So far I can click on a user and create a chat session, using my chatWindow class. But this means I can only create one chatWindow class, called 'chat'. How can I get the application to dynamically make new instances of this class with unique names, for examples chatWindowUser1, chatWindowUser2.
    Below is some code utlising the Openfire Smack API but hopefully the principle is the clear.
        private void chatButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
            int selectedUserIndex = rosterList.getSelectedIndex();
            String selectedUser = rostAry[selectedUserIndex].getUser();
            System.out.println("Chat with: " + selectedUser);
            if (chatBox == null) {
                JFrame mainFrame = CommsTestApp.getApplication().getMainFrame();
                chatBox = new CommsTestChatBox(mainFrame,conn,selectedUser);
                chatBox.setLocationRelativeTo(mainFrame);
            CommsTestApp.getApplication().show(chatBox);
    }  

    yes, an array would work fine, just realize that by using an array, you're setting an upper bound on the number of windows you can have open.
    As for unique names, if you mean unique variable name, you don't need one. The array index serves to uniquely identify each instance. If you mean unique title for the window, set that however you want (username, index in array, randomly generated string, etc.). It's just a property of the window object.

  • Single-instance manual standby for a three-node RAC database

    Hi all,
    I am wondering how it is possible to create a manual standby database for a rac primary database.
    Oracle versione is standard edition 11.1.
    I have experience creating and managing manual standby for single-instance database; I am wondering if and how I can instruct the single-instance standby database to discover and apply the three redo threads that I will copy from the primary site to the standby site.
    Should I use rman to catalog all the archived log on the standby site ?
    Should I configure many LOG_ARCHIVE_DEST_n parameters to point to many different path, one for each primary instance (i.e. one for each redo thread), and let rman automagically discover all the archived logs ?
    Should I configure only LOG_ARCHIVE_DEST_1 , put archivelogs from all threads in the same folder, and let rman automagically discover all the archived logs ?
    Thanks for every answer!
    Andrea

    Hi,
    indeed i catalog all transfered archive logs in front of the recover process.
    During the tests i believe (iirc) i was unable to recover from transfered archivelogs without catalog them first. But this statement is out of my mind, i am not 100% sure for this, sorry.
    Some more details.
    Because it is a standard edition, i have to use on the RAC side ASM. So our normal scripts to transfer archivelogs from primary to standby are obsolete.
    So i decided to put the whole standby thing into the database. Now the primary database uses external scheduler jobs to do the work. The standby side is not using ASM, so there is no need to handle the logs in any special way.
    The steps are:
    1. Get SCN from primary and standby
    2. Transfer the logs for the gap from ASM to "normal" filesystem.
    3. Transfer (and compress, if not in LAN) to standby archive dest
    4. Catalog on standby side
    5. Recover on standby side
    6. Delete on normal filesystem (on both sides, but on standby with a delay of 2 days just to be sure)
    The steps on the standby side are both using the primary scn from step 1 as a parameter to avoid error messages during the catalog or recover call.
    Hth
    Joerg

  • How does a RAC DB 'spread' from single instance to multiple instances ?

    GI/RDBMS Version: 11.2.0.3
    OS: Oracle Linux 6.3
    Filesystem : ASM
    When a RAC database is created using dbca , Manually , or RMAN restore, the DB is created in the Node1 first with cluster_Database=FALSE .
    Then you run the following commands (for 3-node RAC)  from Node1
    srvctl add database -d lmnprod -o $ORACLE_HOME -p +LMNPROD_DATA01/lmnprod/spfilelmnprod.ora
    srvctl add instance -d lmnprod -i lmnprod1 -n hwcarser290
    srvctl add instance -d lmnprod -i lmnprod2 -n hwcarser291
    srvctl add instance -d lmnprod -i lmnprod3 -n hwcarser292
    Once the DB is created,mounted and opened in Node1 and the above commands are executed , you set cluster_Database=TRUE and startup the Instance2 and Instance 3 in Node2 and Node3.
    I just want to know how does Node2 and Node3 becomes aware of the DB and joins the DB cluster ? What happens internally ?

    Generally speaking, registering in OCR is not required for database to be a cluster database.
    Migration from single-instance database to cluster consists of creating redo logs and undo tablespace for new instance and enabling this instance (thread). If database is policy-managed, this is done automatically for new node.

  • 10.2.0.4 patch on single instance standby database

    Hi All,
    We have production database 10.2.0.3 running with RAC having 2 nodes on Solaris 10. We have patched this
    databases to 10.2.0.4 (both nodes) on production without any issue.
    We have a physical standby database (10.2.0.3) with 2 nodes on solaris 10. But we have stopped node2 sometime
    back and currently it's a single instance standby database. Whe nwe are trying to apply patch to standby dataabse
    it's showing both node during installation and installation fails when it tries to search for node2.
    What's the solution for this problem? Any document on how to patch the single instance standby database when
    production is running in RAC.

    I think you are basically saying that you have a 2 node RAC cluster with 1 node down (possibly permanently) and you want to just patch 1 of the nodes?
    It's not overly a surprise the installer is trying to patch the other node, when as far as your inventory is concerned you have a 2 node cluster.
    Have you tried running the installer with the -local option?
    This should just patch your local node. Obviously the dictionary changes will get applied via MRP from the primary db.
    jason.
    http://jarneil.wordpress.com

  • Calling instance method from an instance of a class.

    Hi,
    Can anyone tell me How can i change this TestAccount0 class so that i get the balance from Account class.
    public class TestAccount0
       public static void main(String[] args) {
         Account.deposit(1000);
         System.out.println(Account.getBalance());
    }I have done it this way. I just want to print the balance without* saving the instance of the Account class in any variable in the 1st statement. Can i do it this way?. I have made instance of Account class to access deposit method but how can i print whatever is in the first statement? What can i do to print 1000 as says in the 1st statement because apparently it is printing balance 0.
    Thanks
    public class TestAccount0
       public static void main(String[] args) {
                 (new Account()).deposit(1000);//make instance of Account class to access the method of Account class.
                 System.out.println((new Account()).getBalance());// prints the balance which in this case would be 1000.
    }

    Jas85 wrote:
    So the original code doesn't read Account.deposit(1000) at all?
    I think you can make that work by writing instance of class I.e (new Account()).deposit(1000).(a) please answer the question
    (b) Not unless you want to throw away the Account, and its balance, immediately. Which doesn't make sense, does it?
    Alternatively the original code doesn't look like that at all ...
    ok...you are saying they have given me the wrong code to fix.No, I am saying that either the original code doesn't look like what you posted here, or they have given you an impossible assignment. It should look like this:
    Account ac = new Account();
    ac.deposit(1000);
    System.out.println("balance="+ac.getBalance());

  • Singleton instance vs static class

    Hi,
    I often got confused to identify when is better to use a singleton instance and when is better use a static class insted.
    Could someone please advise what criteria should be observed to decide which way is better?
    Thanks in advance,

    A class with all static methods generally connotes a helper class that supplies behavior or enforces business rules of other objects. A class with only state and no behavior is typically encountered in distributed systems, also known as a transfer object. Most true objects have both state and behavior. A singleton is simply a normal object that ensures only a single instance of itself will ever be created and returned for use to a caller.
    - Saish

  • We are a Global group, with divisions using a single instance of Eloqua

    Any advice on this would be great.
    We are a Gloabl group, with a number of different divisions, offering different I.T services and solutions. Each has its own marketing roadmap to which a single database will be used to target and segment via marketing activity.
    Just after some advice and best practice I suppose, hopefully there is someone out there who has tackled a similar problem ...
    i) What is the best way to target these divisions within a single database, without causing too much of a headache.
    ii) As we have a single instance of ELQ, in terms of differentiating the divisions, is the easy approach to simply set up different email groups for camapigns? I.E, Different Headers, footers and preference centres etc... ???
    Haven't started to consider the ELQ side of things as yet, but was wondering if anyone has tackled this recently, before I deep dive in, and if they have any advice?
    Thanks in advance.

    I agree with all of the above! I will just add a couple of additional suggestions:
    I would really put some effort in your preference center. Make sure you clearly define your opt-in/opt out strategy and the priority of messages to avoid redundancy and unnecessary overlaps. This may require collaboration with other teams upfront but can save you time and headaches in the long run.
    Along with this, your content strategy can benefit from a regular review at a global level to ensure you are still relevant at the division level (which I would assume you already do )
    If you have customers who are likely to be member of multiple divisions,  I would also make sure to run some filters or have a program that checks your set of rules in order to manage email frequency.
    Like Marian suggested, adherence and reinforcement of a solid naming convention for everything will be key.
    Cheers!

Maybe you are looking for

  • Help converting pdf forms to a word document

    Debbie I need help converting a pdf form to a word document.

  • Problems with Embedded Font MS PGothic

    Hello, After editing a document in Japanese, some characters will not show up. Normally i would attribute this to a missing font pack, but after reinstalling the Japanese font pack on the computer, we strill get the error message: "Cannot extract the

  • Is it possible to add / change frequency bands to ...

    Now this question may, after I have all my information, well, it may appear foolish even to ask but I was curious.  I am curious as to whether or not frequency bands can me added or modified on N series phones?  Is this an issue of hardware updates o

  • Can only print 1 page even do I have 2?

    Am trying to print graphics that fills more than 1 page and even do am using Book class to be able print several pages I cant? This is how I try:     public int print(Graphics g, PageFormat pf, int pageIndex)throws PrinterException         shapes.pri

  • Can this iMac be saved?

    I have a 12 year old Imac - Rev B. - System 9.2... 4 Gigs Hard Drive... 168 RAM...This computer has worked very well... never a problem until now. I am a teacher. I was using this computer in my classroom. It was able to surf the web... most of web p