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

Similar Messages

  • Multiple threads access the same method.

    Hello,
    I have been trying for a long time to find out multiple threads access the shared data.
    I have written a sample code, there I my intention is that method has to be accessed
    onlny one thread at a time., mean one thread finished the job, then next thread can
    access the shared source. But for this code I am not getting the desired out put what I want. But if I am using synchronized block I am getting the output. Please correct where I got mistake. Please see my code.
    public class TestThread implements Runnable {
         Shared r;
         public TestThread() {
              r = new Shared();
         public static void main(String args[]) {
              Thread t1 = new Thread(new TestThread());
              Thread t2 = new Thread(new TestThread());
              t1.setName("A");
              t2.setName("B");
              t1.start();
              t2.start();
          * (non-Javadoc)
          * @see java.lang.Runnable#run()
         @Override
         public void run() {
              // TODO Auto-generated method stub
              r.count();
    class Shared {
         public synchronized void count() {
              String name = Thread.currentThread().getName();
              System.out.println(name + ":accessed...");
              try {
                   for (int i = 0; i < 5; i++) {
                        System.out.println(name + ": " + i);
              } catch (Exception e) {
                   // TODO: handle exception
    }Thanks
    Bhanu lakshmi.

    It depends on what you synchronize. Non-static methods synchronize on the object, so if you're using several objects, you'll be able to call each from their own thread.
    Make your method synchronized or use only a single object and see the difference.

  • 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 ?

  • Berkeley DB Java Edition - multiple threads accessing database

    Hi,
    I would like to access (read & write) a Berkeley DB from multiple threads (all same process/jvm).
    Should I use a single com.sleepycat.je.Database object for all threads, or should I create an instance for each?
    Or is there any other way of doing it?
    Thanks

    The Database object may be used by multiple threads, so you can use a single instance or multiple ones, as best suits you. From http://docs.oracle.com/cd/E17277_02/html/java/com/sleepycat/je/Database.html,
    Database handles are free-threaded and may be used concurrently by multiple threads. 'If you read through the javadoc, you'll find other notes on using classes from multiple threads.
    Regards,
    Linda

  • Problem with multiple threads accessing the same Image

    I'm trying to draw into one Image from multiple threads. It works fine for a while, but then suddenly, the image stops updating. Threads are still running but the image won't update. I'm using doublebuffering and threads are simply drawing counters into Image with different speed.
    It seems like the Image gets deadlocked or something. Anyone have any idea what's behind this behavior or perhaps better solution to do such thing.
    Any help will be appreciated.

    Sorry Kglad, I didn't mean to be rude. With "No coding
    errors" I meant the animation itself runs with no errors. I'm sure
    you could run the 20 instances with no freezing (that's why I put
    the post :) ) But I'm affraid it is an animation for a client, so I
    cannot distribute the code.
    Perhaps I didnt explain the situation clearly enough (in part
    because of my poor english...).-
    - By 20 instances I mean 20 separated embedded objects in the
    html
    - The animation is relatively simple. A turned on candle, in
    each cycle I calculate the next position of the flame (that
    oscilates from left to right). The flame is composed by 4
    concentric gradients. There is NO loops, only an 'onEnterFrame'
    function refreshing the flame each time.
    - It's true that I got plenty variables at the _root level.
    If that could be the problem, how can I workaround it?
    - It is my first time trying to embed so many objects at the
    same time too. No idea if the problem could be the way I embed the
    object from the html :(
    - The only thing I can guess is that when a cycle of one of
    the object is running, the other 19 objects must wait their turn.
    That would explain why the more instances I run, the worst results
    I get. In that case, I wonder if there's a way to run them in a
    kind of asynchronous mode, just guessing...
    Any other comment would be appreciated. Anyway, thanks a lot
    everybody for your colaboration.

  • Configuring multiple services in a single instance database

    Dear All,
    I would like to create multiple service names for a single instance oracle database (10.2.0.3 on IBM - AIX 6.1). I tried searching on the net, reading documentation, and also on the metalink but couldn't find anything relevant to single instance database.
    Say I have two users, userA and userB, for which I would like to use two services (ServA and ServB) to connect to the same single instance database.
    Any help in this direction is appreciated.
    Regards

    Oracle Lover3 wrote:
    Thanks for your quick solution.
    By the time you answered I was able to locate it in the documentation. I have tested it and its working perfectly. Here's the documenation link.
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/initparams188.htm#i1133481
    It is very hard to believe you didn't find this in the documentation, and my suspicion is you didn't search for it at all.It is very hard to believe that you don't trust others and end up in suspicion. I wish you were sitting next to me while I was searching for the link/document.It is because the vast majority of doc questions are asked by people who don't read the docs at all.
    Now, I'm curious about your requirement. While it can be done, it is pretty unusual. That always leads me to want to step back from the technical question and ask What business problem is this solving?

  • 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 :(

  • 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...

  • How to access multiple database present in single instance

    Hi Team,
    In oracle 11.2, can there be multiple databases in an instance???  In one of our environment, I could see multiple databases in an instance. Could you please help me in giving the data dictionary or query to access those databases?
    Actually, querying v$database, I could see only one database which is same as instance name. But in inventory, there are multiple database in an instance?
    I am still not exactly clear about this. Can someone help me with this?
    Thanks!
    Vidhya

    In Oracle one instance manages one (1) database. A database consists of multiple *schemas*.
    Other vendors erroneously call a schema 'database'.
    So, no, you didn't see multiple databases.
    There is also one datadictionary, consisting of a set of views.
    All views beginning with dba_  list the entire database, all schemas.
    All views beginning with all_ list the objects you have access to.
    All views beginning with user_ list your own objects.
    The view DICT show you the contents of the datadictionary.
    Oracle also has online documentation at http://docs.oracle.com
    From your question it is clear you should read the document called the 'Oracle Concepts Manual'.
    You can find all documentation for 11gR2 here Oracle Database Online Documentation 11g Release 2 (11.2)
    Too many people here don't make any effort to read it. This is probably the reason why you got no response.
    Sybrand Bakker
    Senior Oracle DBA

  • Can multiple  hosts exist on single instance

    Hi B2B gurus,
    I would like to present a scenario i am trying to work out.
    Lets say there are 2 buyers B1 and B2
    And 2 suppliers S1 and S2.
    The buyers send a PO to the supplier and the lets say the Supplier sends an Invoice to the Buyer.
    Also there are 8 agreements in all. I mean all possible combinations such that a buyer can send a PO to any supplier and a Supplier can send a invoice to any Buyer.
    My understanding of B2B is that it is generally a single Host TP and there can be multiple remote TP's.
    To make my scenario work we will need multiple host TP's. One solution for this is to install N instances of B2B. But that is not feasible.
    So is it possible to install only one instance of B2B and create multiple Host TP's and multiple agreements as i wanted.
    We can use an API or something similar for this, so that this can all be done through the backend.
    I agree that this may seem a little confusing, so if you have any queries feel free to ask them
    Thanks
    Ravi
    Edited by: Ravi R on Apr 27, 2009 4:47 PM

    I did read the two forums you have mentioned, from this my understanding is the following.
    Without tweaking the current B2B sytem i can have one TP send multiple format documents to multiple TP's without any problems.
    Eg B1 can send to S1 a PO over email . B1 can also send a Change Order to S1 via AS2/FTP?any other method.
    Is my understanding correct??
    So if i were to use the hub model as you suggested i will use different identifiers to identify multiple buyer TP's
    And hence there will be lotsa agreements all on the basis of identifiers and doc received and that will decide the target doc format and the transport delivery method.
    Qn 1 - Does this seem to make sense? (feasibility, possible issues )
    Qn 2 - What will be the performance consideration? Is there any performacne guide or so ??
    Edited by: Ravi R on Apr 28, 2009 11:53 AM

  • Can I manage multiple devices from a single iTunes account?

    Currently have (2) iPhones, and iPOD and planning on acquiring a iPAD Can use a single iTunes account to manage all of these devices?

    Here are some tips: How to use multiple iPods, iPads, or iPhones with one computer, http://support.apple.com/kb/HT1495

  • Multiple ESS access to single EP server from two backend servers.

    Hi Experts,
    I have one concern regarding ESS.
    Can we do or can we make   two ESS access (R3 server1 and R3 Server2)  from one Portal server.
    I heard  that from one portal server (ESS)  we can connect multiple clients which are from backend R3 (example client 100 and client 200)
    My requirement is  :
    We have two R3 backend servers and one EP(ESS) server.
    Can we access two backend systems from one EP server with Two ESS tabs.
    I am expecting Multiple jco settings, multiple SSo, Multiple SLD, Multiple SPRO Menu settings, UWL settings.
    Multiple service specific settings to be access  by using  single EP server(Multiple ESS Tabs)
    Please help me for doing this.
    Regards
    Kumar.

    yes you can do so As Pooja indicated also refer
    Please have a look  at the Note 596698
    Thanks for clearing that up, Now if I understand the issue
    correctly :
    1 Portal, Two backend R/3 System, This can be done, Now then
    if you dont want the particular application disable that
    r/3 as you are aware that the links appear from V_T7XSSSERRES.
    Here you can also make sure some applications appear or no.
    Accessing multiple Backends in WebDynpro:
    How it can be done?
    1) Define different JCO Destinations
      The logical System names have to be defined in the Web Dynpro Content
    Administrator.
      Different clients or completely different Systems can be accessed
    given that the function modules called exist in those systemsThe logical System to be used can be passed to the Web Dynpro
    Application by using a URL Parameter
      The URL Parameter can be easily maintained in the iView Property when
    using the portal.
    The standard way to handle this is to create copies (via delta-link) of
    all the business package iviews and change the 'System' property in the
    newly created iviews to point to the correct system Alias. From the
    portal point of view this is all that is required in order to point an
    view to a different system
    Refer these links for further information:
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.
    docs/library/webas/webdynpro/How%20to%20Use%20the%20Web%20Dynpro%20Conte
    nt%20Administrator.pdf

  • Multiple thread pools under single executor

    I would like to segregate the tasks running in an Executor so that certain tasks (perhaps identified by an annotation) could be restricted to a thread pool of a limited size while others run in a different pool.
    The intend is to limit certain crunchy tasks so that they don't saturate a limited resource.
    As far as I can tell I can't do this with a ThreadPoolExecutor even with a custom ThreadFactory. The original Callable is wrapped a couple of times by the time the ThreadFactory.newThread method is called so I can't inspect it at that time. Also, once the maximumPoolSize is reached the waiting tasks will get handed off to whichever thread finishes first, thus making my fixed pools useless.
    I have a feeling that I will need to write my own ThreadPoolExecutor but I thought that I would ask if there was a way to do this with the existing classes first.
    Thanks.

    I used to do this.
    The problem comes in managing the work that flows between the queues, and managing the results. I need to be able to take the output from one task and feed it into another, potentially running in a different thread pool.
    Multiple queues mean waiting for more than one blocking event, which means multiple management threads with a meta-event queue feeding back to an dispatcher that does the messaging.
    With multiple management threads you have to poison all of those queues so that the thing shuts down when you are done.
    By the time that I'm done I may be better off just modifyingThreadPoolExecutor to do what I want. One work queue keeps the shutdown problem under control.
    Thanks for the feedback.

  • Multiple Receive location but Single Instance of Orchestration

    Hi,
    I have only one Receive Port (POP3 adapter) and multiple receive locations configured to different email IDs.
    ReceivePort1
    - Receive location1 - [email protected]
    - Receive location2 - [email protected]
    - Receive location3 - [email protected]
    If I send a mail with more than 1 recipient then that many orchestration instance is being generated.
    If I send a email where 'To' field has all three email Id also, always orchestration should instantiated only once. If I make my Orchestration as Singleton, does it help?
    Regards,
    Lakshmi

    Hi Laxme,
    Ask the team which manages the mailboxes to create a rule for these different emailIDs. The rule should route the mails (which you want to process in BizTalk, so you can have filter) to these email ID/ mailboxes to another email ID/mailbox something like
    [email protected]
    Then create a Receive port and Receive Location to receive emails from
    [email protected] In the port’s inbound map, apply map to convert the incoming message to the different mailbox to an canonical (common) schema
    Create a orchestration to receive message of type of the canonical (common) schema
    Define correlation set and types and in the correlation properties we will use the “BTS.ReceivePortName” property. This will enable you to have the convoy configured on all the messages arriving on a particular receive port. And define a singleton orchestration,
    if you want to have one instance of the orchestration created. Since you will have one mailbox to receive messages you can process the message in your orchestration even without the singleton orchestration depending on your actual processing requirements.
    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.

  • Slow performance when multiple threads access static variable

    Originally, I was trying to keep track of the number of function calls for a specific function that was called across many threads. I initially implemented this by incrementing a static variable, and noticed some pretty horrible performance. Does anyone have an ideas?
    (I know this code is "incorrect" since increments are not atomic, even with a volatile keyword)
    Essentially, I'm running two threads that try to increment a variable a billion times each. The first time through, they increment a shared static variable. As expected, the result is wrong 1339999601 instead of 2 billion, but the funny thing is it takes about 14 seconds. Now, the second time through, they increment a local variable and add it to the static variable at the end. This runs correctly (assuming the final increment doesn't interleave which is highly unprobable) and runs in about a second.
    Why the performance hit? I'm not even using volatile (just for refernce if I make the variable volatile runtime hits about 30 seconds)
    Again I realize this code is incorrect, this is purely an interesting side-expirement.
    package gui;
    public class SlowExample implements Runnable
         public static void main(String[] args)
              SlowExample se1 = new SlowExample(1, true);
              SlowExample se2 = new SlowExample(2, true);
              Thread t1 = new Thread(se1);
              Thread t2 = new Thread(se2);
              try
                   long time = System.nanoTime();
                   t1.start();
                   t2.start();
                   t1.join();
                   t2.join();
                   time = System.nanoTime() - time;
                   System.out.println(count + " - " + time/1000000000.0);
                   Thread.sleep(100);
              catch (InterruptedException e)
                   e.printStackTrace();
              count = 0;
              se1 = new SlowExample(1, false);
              se2 = new SlowExample(2, false);
              t1 = new Thread(se1);
              t2 = new Thread(se2);
              try
                   long time = System.nanoTime();
                   t1.start();
                   t2.start();
                   t1.join();
                   t2.join();
                   time = System.nanoTime() - time;
                   System.out.println(count + " - " + time/1000000000.0);
              catch (InterruptedException e)
                   e.printStackTrace();
               * Results:
               * 1339999601 - 14.25520115
               * 2000000000 - 1.102497384
         private static int count = 0;
         public int ID;
         boolean loopType;
         public SlowExample(int ID, boolean loopType)
              this.ID = ID;
              this.loopType = loopType;
         public void run()
              if (loopType)
                   //billion times
                   for (int a=0;a<1000000000;a++)
                        count++;
              else
                   int count1 = 0;
                   //billion times
                   for (int a=0;a<1000000000;a++)
                        count1++;
                   count += count1;
    }

    Peter__Lawrey wrote:
    Your computer has different types of memory
    - registers
    - level 1 cache
    - level 2 cache
    - main memory.
    - non CPU local main memory (if you have multiple CPUs with their own memory banks)
    These memory types have different speeds. Depending on how you use a variable affects which memory it is placed in.Plus you have the hotspot compiler kicking in sometime during the run. In other words for some time the VM is interpreting the code and then all of a sudden its compiled and executing the code compiled. Reliable micro benchmarking in java is not easy. See [Robust Java benchmarking, Part 1: Issues|http://www.ibm.com/developerworks/java/library/j-benchmark1.html]

Maybe you are looking for

  • How to search source of pl/sql block in database?

    Hi Guys, We have an issue in database, there is PL/SQL block running in my database as below which deleting very important historical data. begin loop delete from tabl_name where created_date<sysdate -100 and ronum<10000; EXIT WHEN SQL%NOTFOUND; comm

  • "Bridge is running low on memory and should be restarted" error

    I am running Bridge CS4 on a DELL T-1650 with plenty of hard drive space.  I am having trouble with indexing / caching files.  My computer is connected to a large office server with a large amount of files that I need to be able to search.  I recieve

  • Event 03 in table maintenance generator

    Hello All, I have created a event 03 in table maintenance generator. Because I need to check if the deleted key is still referenced in an other table. I tried the following code, but only if I use the message the entry will not be deleted.   MOVE ueb

  • Horizontal Menu in IE6

    Created a horizontal menu works great in all browsers but IE6, http://www.remodelersoutlet.com. I posted in the forum a couple of weeks ago but no response so I'm giving it another try. I think the problem is with visited links, but can't resolve. He

  • Nokia N81 8gb Screen goes crazy

    ok so i buaght my Nokia N81 like in january last year and ive been using it quiet regularly.... Until today... I slid the phones slider to reveal the keys to write a text message, when the screen went crazy with funky colours and such lines and rando