Make sure 2 threads share the same object

I have been thinking about this for quite some time. However, I really couldn't figure it out due lack of experience and knowledge.
I just needed to know how can I make sure that 2 or more threads (after certain checkings that they should share a same common object) will really share the same object.
For example (to UlrikaJ if you are reading this):
How can I achieve the following?? Thanks!
"When James and Ada separately want to access their shared account,two transactions are started that accesses the object associated with that account number."

Thanks for the answer. You are welcome :-)
public class Account
   public Account getAccount(String userInput)
     // Some processes to verify the userInput go here.
     return account;
}//End of Account class
public UserThread implements Runnable
   private String name;
   private Semaphore s;
   private Account userAccount; //Reference for the Account class
   public UserThread(String name, Semaphore s)
      this.name = name;
      this.s = s;
   }//End of constructor
   public void run()
      for(;;)
          getUserInput(); //Ofcourse the implementation will depend on what you are doing
          s.lock(); //obtain a lock on Semaphore object
          //Entering critical section of the code
          this.userAccount = accountObject.getAccount(userInput);
          //End of critical section of the code.
          s.signal(); //Release the lock so that other thread
          //can access the getAccount() method...irrespective of the
          //variable or the object being used or referred to.
      }//End of for() loop
   }//End of run() method
} //End of UserThread class
public class AccountApplication
   public static void main(String args[])
      Semaphore sem = new Semaphore(0);
      //Always initialize the Semaphore with 0 when you create it.
      UserThread user1 = new UserThread("User Number 1",sem);
      UserThread user2 = new UserThread("User Number 2",sem);
      //All threads share the same Semaphore object
      Thread userThread1 = new Thread(user1);
      Thread userThread2 = new Thread(user2);
      userThread1.start();
      userThread2.start();
   }//End of main() method
}//End of classWell, I have given the outline of the code. I have not compiled or run the program so it might have errors in its syntax.
Obviously, you will definitely have to change it to suit your requirements. I have just shown you how to protect yur codes' critical section.
Hope this clears your doubts.
Vijay :-)

Similar Messages

  • Can multiple threads share the same cursor in berkeley db java edition?

    We use berkeley db to store our path computation results. We now have two threads which need to retrieve records from database. Specifically, the first thread accesses the database from the very beginning and read a certain number of records. Then, the second thread needs to access the database and read the rest records starting from the position where the cursor stops in the first thread. But, now, I cannot let these two threads share the same cursor. So, I have to open the database separately in two threads and use individual cursor for each thread. This means I have to in the second thread let the cursor skip the first certain number of records and then read the rest records. However, in this way, it is a waste of time letting the second thread skip a certain of records. It will be ideal for us that the second thread can start reading the record just from the place where the first thread stops. Actually, I have tried using transactional cursor and wanted to let the two threads share the same transactional cursor. But it seems that this didn't work.
    Can anyone give any suggestion? Thank you so much!
    sgao

    If your question is really about using the BDB Java Edition product please post to the JE forum:
    Berkeley DB Java Edition
    If your question is about using the Java API of the BDB (C-based) product, then this is the correct forum.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Two Threads Sharing the Same Object

    I am learning Java multithreading recently and I really hit the wall when I came to synchronizing data using the synchronized keyword. According to the explanation, synchronized will only work when 2 or more threads are accessing the same object. If there are accessing 2 different objects, they can run the synchronized method in parallel.
    My question now is how to make sure for synchronized method to work, I am actually working with the same and only one object??
    Imagine this:
    Two person with the same account number are trying to access the very ONE account at the same time.
    I suppose the logic will be:
    Two different socket objects will be created. When it comes to the login or authentication class or method, how can I make sure in term of object that the login/authentication class or method will return them only ONE object (because they share the same account), so that they will be qualified for using the synchronized method further down the road?
    Thanks in advance!

    Actually your understanding is wrong. Consider:
    public class MyClass {
      private int someInt;
      private float someFloat;
      private synchronized void someMethod(final int value) {
        if (value > 2000) someInt = 2000;
      private synchronized void someOtherMethod(final float value) {
        if (value > 2.0) someFloat = 1.999f;
    }YOu might think that two different threads can enter this code, one can enter in someOtherMethod() while one is in someMethod(). That is wrong. The fact is that synchronization works by obtaining synchronization locks on a target object. In this case by putting it on the method declaration you are asking for the lock on the 'this' object. This means that only one of these methods may enter at a time. This code would be better written like so ...
    public class MyClass {
      private int someInt;
      private float someFloat;
      private void someMethod(final int value) {�
        synchronized(someInt) {
          if (value > 2000) someInt = 2000;
      private void someOtherMethod(final float value) {
        synchronized(someFloat) {
          if (value > 2.0) someFloat = 1.999f;
    }In this manner you are only locking on the pertinent objects to the method and not on 'this'. This means that both methods can be entered simultaneously by two different threads. However watch out for one little problem.
    public class MyClass {
      private int someInt;
      private float someFloat;
      private void someMethod(final int value) {�
        synchronized(someInt) {
          if (value > 2000) {
            someInt = 2000;
            synchronized (someFloat) {
              someFloat = 0.0f;
      private void someOtherMethod(final float value) {
        synchronized(someFloat) {
          if (value > 2.0) {
            someFloat = 1.99999f;
            synchronized (someInt) {
              someInt = 0;
    }In this case you can have a deadlock. If two threads enter one of these methods at the same time one would be waiting on the lock for someInt and the other on the lock for someFloat. Neither would proceed. The solution to the problem is simple. Acquire all locks in alphabetical order before you use the first.
    public class MyClass {
      private int someInt;
      private float someFloat;
      private void someMethod(final int value) {�
        synchronized (someFloat) {
          synchronized(someInt) {
            if (value > 2000) {
              someInt = 2000;
              someFloat = 0.0f;
      private void someOtherMethod(final float value) {
        synchronized(someFloat) {
          if (value > 2.0) {
            someFloat = 1.99999f;
            synchronized (someInt) {
              someInt = 0;
    }In this manner one thread will block waiting on someFloat and there can be no deadlock.

  • How to make two portals share the same UME?

    Hi all,
    Can anybody share some information about how to make two portals share same UME? Is it possible? Thanks.
    B.R.

    Hi Lee,
    Its very much possible for 2 portals to make use of one datasource for UME.
    Lets assume for a scenario sake we are using an LDAP server as the UME for portals environment...so you would simple need to point for the UME's to the LDAP datasource.
    If you have something in particular do post back
    Thanks,
    GLM

  • How to make sure 2 Variables of same class do not share internal variables?

    K, I am having trouble making a new instance of an object.
    I have a class call File_Class that have a public static attribute call File_Name.
    Now in another class, I have a linkedlist and each one of the element is supposely a File_Class object. The problem that I am having now is that whenever I create a new File_Class (File_Class New_Class = new File_Class (File_Name)), i am actually getting a reference to the old one so that anything that I change reflects on every element of my link list.
    My question now is
    1. how exactly do i enforce that a new instance of the object (File_Class) is created so i can make sure every element in my linked list is distinct.
    2. why is this happening at all
    thanks for your help in advance.
    Hung-Hsun Su

    Here is a simple example that i wrote just to demonstrate the point. it seems that i always get the same object no matter what. Thanks again.
    Result:
    AFTER 0 1 2
    1 2
    AFTER 1 10 20
    10 20
    10 20
    AFTER 2 99 999
    99 999
    99 999
    99 999
    Code:
    class T
              public static int A;
              public static int B;
    class Test
              static T TA[] = new T[5];
              private static void Set_Value (int i, int A, int B)
                        T t1 = new T ();
                        t1.A = A;
                        t1.B = B;
                        TA[i] = t1;
              private static void Print (int i)
                        for (int k = 0; k <= i; k++)
                                  System.out.println (TA[k].A + " " + TA[k].B);
              public static void main (String args[])
                        System.out.println ("AFTER 0 1 2");
                        Set_Value (0, 1, 2);
                        Print (0);
                        System.out.println ("AFTER 1 10 20");
                        Set_Value (1, 10, 20);
                        Print (1);
                        System.out.println ("AFTER 2 99 999");
                        Set_Value (2, 99, 999);
                        Print (2);
         }

  • HT5177 How can two people edit the same FCPX file? One company, so both people/computers share the same license. Example: I work on revision A and my boss takes it and makes revision B and gives it back to me using two separate computers.

    How can two people edit the same FCPX file? One company, so both people/computers share the same license. Example: I work on revision A and my boss takes it and makes revision B and gives it back to me using two separate computers.

    Have the project, events and media on one drive which is common to both macs.
    You can download FCP X to both macs using the same Apple ID that it was purchased with.
    Andy

  • HT204053 How do i make icloud work if my husband and I share the same itunes account but we dont want to get each others contacts, messages, apps etc?

    How do i make icloud work if my husband and I share the same itunes account but we dont want to get each others contacts, messages, apps etc?

    Each of you should set up your separate iCloud account on your own computer using your Apple ID. This gives you two independent iCloud accounts.
    Note that an iPad is not a multi-user device. It can only be synced with one account.

  • How can I make two single BI Servers share the same presentation catalog?

    Hi all,
    I have two single BI Servers(not in the cluster).Now,I want the two Servers can share the same presentation catalog. How can I do it?
    Thanks in Advance!

    Select the lines > Format menu > Advanced > Move Object to Section Master

  • I have the IPhone, IPad and MacBook, IPad and IPhone share the same Apple ID and Icloud storage. Cannot make ID Change on MacBook as it says the ID is already taken. How can I make all three match?

    I have the IPhone, IPad and MacBook, IPad and IPhone share the same Apple ID and Icloud storage. Cannot make ID Change on MacBook as it says the ID is already taken. How can I make all three match?

    The problem is that all services are bundled with your Apple ID ([email protected]):
    Your iCloud account (Mail, Contacts, Calendars, Reminders, Notes, Backups, etc.),
    also iTunes & App Store purchases (Music, Movies, TV Shows, etc.),
    and the iTunes Match services.
    (I guess that all your devices - yours and your wife's are connected to one iTunes library, right?)
    If you want that your wife gets her own iCloud account for Mail, Contacts, Calendars, etc. but gets also access to your media then you have two set up two things on her device:
    iCloud (Settings > iCloud) with her account (e.g. [email protected])
    and
    iTunes & App Stores (Settings > iTunes & App Stores) with your account (e.g. [email protected]).
    In this case she gets access to your library and could use the same iTunes Match account.
    (See also: Using one Apple ID for iCloud and a different Apple ID for Store Purchases http://support.apple.com/kb/HT4895)

  • I cant use facetime. but my sister can. we share the same account for itunes.but when i go to face itme and click on create a new account a blank screen pops up. what do i do?when i go to make a new facetime account nothing comes up

    i cant use facetime. but my sister can. we share the same account for itunes.but when i go to facetime on my ipod touch and click on create a new account a blank screen pops up and the only thing it says is cancel and account.  what do i do?

    Please follow these directions to delete the Mail "sandbox" folder.
    Back up all data.
    Triple-click the line below to select it:
    ~/Library/Containers/com.apple.mail
    Right-click or control-click the highlighted line and select
    Services ▹ Reveal
    from the contextual menu.* A Finder window should open with a folder named "com.apple.mail" selected. If it does, move the selected folder — not just its contents — to the Desktop. Leave the Finder window open for now.
    Quit and relaunch Mail, and test. If the problem is resolved, you may have to recreate some of your Mail settings. You can then delete the folder you moved and close the Finder window. If you still have the problem, quit Mail again and put the folder back where it was, overwriting the one that may have been created in its place. Post your results.
    Caution: If you change any of the contents of the sandbox, but leave the folder itself in place, Mail may crash or not launch at all. Deleting the whole sandbox will cause it to be rebuilt automatically.
    *If you don't see the contextual menu item, copy the selected text to the Clipboard (command-C). In the Finder, select
    Go ▹ Go to Folder...
    from the menu bar, paste into the box that opens (command-V). You won't see what you pasted because a line break is included. Press return.

  • How do I use multiple classes to access the same object?

    This should be staightforward. I have and object and I have multiple GUIs which operate on the same object. Do all the classes creating the GUIs need to be inner classes of the data class? I hope this question makes sense.
    Thanks,
    Mike

    public final class SingletonClass {
    private static SingletonClass instance;
    private int lastIndex = 10;
    public final static SingletonClass getInstance()
    if (instance == null) instance = new SingletoClass();
    return instance;
    public int getLastIndex() {
    return lastIndex;
    }1) This won't work since one could create a new SingletonClass. You need to add a private constructor. Also, because the constructor is private the class doesn't have to be final.
    2) Your design isn't thread-safe. You need to synchronize the access to the shared variable instance.
    public class SingletonClass {
        private static SingletonClass instance;
        private static Object mutex = new Object( );
        private int lastIndex = 10;
        private SingletonClass() { }
        public static SingletonClass getInstance() {
            synchronized (mutex) {
                if (instance == null) {
                    instance = new SingletonClass();
            return instance;
        public int getLastIndex() {
            return lastIndex;
    }if you are going to create an instance of SingletonClass anyway then I suggest you do it when the class is loaded. This way you don't need synchronization.
    public class SingletonClass {
        private static SingletonClass instance=new SingletonClass();
        private int lastIndex = 10;
        private SingletonClass() { }
        public static SingletonClass getInstance() {
            return instance;
        public int getLastIndex() {
            return lastIndex;
    }If you don't really need an object, then you could just make getLastIndex() and lastIndex static and not use the singleton pattern at all.
    public class SingletonClass {
        private static int lastIndex = 10;
        private SingletonClass() { }
        public static int getLastIndex() {
            return lastIndex;
    }- Marcus

  • How can I share the same music but separate calendars and address book for 2 users on the same computer?

    Can anyone help to answer if I can share the same music account on itunes but still maintain separate calendars and address books on the same computer?

    Make sure each user has their own computer login.
    Copy the entire /Music/iTunes/ folder to /Users/Shared.
    Hold Option and launch iTunes.
    Select Choose library and select /Users/Shared/iTunes/ folder.
    Quit iTunes and log into other user.
    Hold Option and launch iTunes.
    Select Choose library and select /Users/Shared/iTunes/ folder.
    That is all you need to do.
    Any changes in iTunes by one will be seen by all others (since you are using the same library).
    All users will have their own Contacts & Calendars and all other info.
    If you are using Fast User switching, you must quit iTunes before switching users if others wish to use iTunes.

  • Can 2 apple ids share the same library..ie music, videos,apps ect

    I have an apple id and my wife would like to get her own as well, but we would like to share the same library, music, apps, books, ect.  We are trying to avoid paying twice for same items but want our own id for ichat and personnel devices.  Is this possible and if so how can I do this?

    If you want to share a single AppleID with a single iTunes Library, then simply sync both devices to that iTunes library using the same user account.
    If you want to sync two AppleIDs to one iTunes library, in iTunes on the computer, login and authorize each AppleID, then sync the devices to that common iTunes library in the same user account.
    You do not do anything on the device being sync'd itself - it all has to do with how iTunes that you are syncing to is set up and what AppleIDs are authorized there.  You can sync multiple devices to iTunes, just be sure that each device gets a unique device name in the iTunes sidebar.
    To then use unique AppleIDs for iCloud and iMessage on a iOS device, first, make an iCloud account with the AppleID you want to use (go to http://www.iCloud.com), then set up that iCloud account on the device with that ID and password.  In iMessage, just log out with whatever AppleID you are using now, log in with the new AppleID and it will reauthorize, now linking that device with the new iMessage account just created with that AppleID (your iMessage primary account ID is always the AppleID used to initially create and verify the iMessage account).

  • Two kids/Two iPods - share the same apps?

    I just bought my kids iPods. My daughter already has a gmail that I setup with my information so she has her own AppleID.
    They like the same music and games - I would like to be able for them to share music and apps.
    How can I do this?? If they share the same AppleID, how will this impact iMessage or Facetime??
    Don't they need their own AppleIDs for that??
    Please help! I'm dealing with nagging kids!!

    Create a NEW account/ID for for each iPod using these instructions. Make sure you follow the instructions. Many do not and if you do not you will not get the None option. You must use an email address that you have not used with Apple before. You have to specify a birtdate that results in a n age of at least 13 years.
    Creating an iTunes Store, App Store, iBookstore, and Mac App Store account without a credit card
    Use the new ID on her iPod but only for:
    Settings>Messages>Send and Receive
    Settings>FaceTime
    and Settings>iCloud if you want her to have separate Contacts Calendar and some other things.
    Continue to use the same/common Apple ID for Settings>iTunes and App stores so you can share purchases.

  • All users share the same iCal

    I want all the users on my iMac to share the same Calendar. How do I do it?

    Here's how to share iCal calendars among multiple users on a single Mac.
    What you need to do is to move the iCal folder to a shared folder that is accessible to all users and then replace the iCal folder in each user's library folder with a "symbolic link' to the shared iCal folder. The symbolic link looks like an "alias", but if you try this using "aliases" to the shared iCal folder it will not work (trust me). You can create symbolic links using the Terminal, but I have no idea how, and the idea of using the Terminal scares me. The easiest way that I know of to create a symbolic link is with a shareware application called Cocktail. It allows you to do a number of different things including System Maintenance, Network Optimization, etc. It took me a while to remember how to do this; I originally found the information in the Discussions when iCal was first released, but apparently none of those original postings are listed in the forums anymore.
    Here's how to do it (you must have Administrator privileges):
    First locate your iCal folder (your user name > Library > Application Support > iCal) and make a copy of it (Finder > File > Duplicate). Drag the copy to your Desktop until you're sure iCal is being shared between users.
    Next move the original iCal folder into a Shared folder in the Users folder (Hard Disk > Users > Shared > iCal). To make sure all users can access the information, select the Shared folder, choose File > Get Info, click the little Lock icon, then under "Ownership & Permissions -> Details" make sure that the "Owner" is "System", "Group" is "Wheel" and "Access" for Owner, Group and Others is "Read & Write". Do the same with the iCal folder within the Shared folder, but this time, under "Ownership & Permissions -> Details" make sure that the "Owner" is "your user name", "Group" is "Staff" and "Access" for Owner, Group and Others is "Read & Write" and click the "Apply to Enclosed Items" button. I basing this information on what the Ownership & Permissions are for each of the folders in my system.
    Open Cocktail (I'm using version 3.6.5). Once the app is open (you must enter an administrator's user name and password) click on the "Files" button, then click on the "Links" button. Where it says "Create Symbolic Link" click on the "Choose" button. Navigate to the iCal folder (Hard Disk > Users > Shared > iCal) and click "Choose" again. In the "Save As" box that appears enter "iCal", then navigate to the Application Support folder in your Home folder (your user name > Library > Application Support) and click "Save". Quit Cocktail and open iCal. You should see all of your calendars as you did before.
    Log in under each additional User, move that User's iCal folder (user name > Library > Application Support > iCal) onto the Desktop, then create another Symbolic Link to replace it, using Cocktail as described above. In each case you should see the same calendar information as when you were logged in under your user name. As a test, add a New Event or To Do in iCal under one user, log out and back in under another user and you should see the changes when you open iCal.
    Once everything appears to be working, you can delete the iCal folders from each User's Desktop.
    As an additional maintenance measure, use Disk Utility to repair Disk Permissions.
    Unfortunately, if each User has his/her own calendars in iCal they will not be in the shared calendars. Only the calendars in the first iCal folder used to set up the shared folder will be available and I don't know of any way to merge or combine the other user's calendars into one.
    Hope this helps and good luck!

Maybe you are looking for

  • Ext Drive Crashed after 10.5.8 Update

    Hi all. I'm wondering if anyone else has had problems with external drives after the 10.5.8 update (I saw the Drobo thread)? I have a 750GB drive in an external Firewire 800 enclosure that was running fine before the update but immediately after it w

  • Working with Flat files in OWB

    I am getting flat files from mainframe tables and I created external tables in OWB for mapping. I get data from flat files sometimes and I dont get data even though the file exists and there is no way to debug where the problem is in the files. When

  • Strange IDE behaviour on i915GM Speedster

    Hello all, I've a small problem : I can connect my DVD reader or my DVD writer, but not both at the same time! If I connect both (only one P-ATA port on this motherboard), Windows freezes just before user login or sometimes just after getting on the

  • Outbound character sets

    Hi Our outbound external messages go out via a GW704 GWIA. The GWIA thenpasses them onto our email security gateway. The issue that I'm having is that I've enabled a 'disclaimer' on our email security gateway that is stamped on all outbound messages.

  • A puzzle game using Flash Builder Burrito

    I used the Flash Builder Burrito and AIR 2.5.1 to build a simple puzzle game for the Android market. It is called 'Ramanujam's Magic Square' and is live. Performance on Galaxy S is as good at it can be with a native app. considering that the puzzle i