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.

Similar Messages

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

  • Two threads in the same class ? Is that possible ?

    Hello, I am trying to use threads to move two images around the frame. And I am wondering if it is possible if it is possible to create two separate threads that act differently in the same class, for each of the image.
    Is just that so far I can't see a way since, by implementing Runnable, I'll need to overwrite the run() method. Which in a way just allows me to manage one image.
    Of course I can do two separate classes (each implementing Runnable) for each of the image, but since I think it may be an overkill, I rather to do it in just one.
    So, is that possible ?
    Thank you in advance.

    Of course I can do two separate classes (each implementing Runnable) for each of the image,Use two instances of the same class. Something like this example:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=631379

  • How to avoid two threads creating the same entity?

    I seem to have a problem with a race-condition. Two threads are trying to
              create the same entity. One thread calls a finder with no success and
              creates the entity, meanwhile - before the entity gets persisted
              (ejbStore()) - the other thread also calls a finder with no success,
              creating the
              same entity.
              My transaction isolation level in the weblogic-ejb-jar.xml is
              <transaction-isolation>
              <isolation-level>TRANSACTION_READ_UNCOMMITTED</isolation-level>
              <method>
              <ejb-name>ejb</ejb-name>
              <method-name>*</method-name>
              </method>
              </transaction-isolation>
              I've also tried <isolation-level>TRANSACTION_SERIALIZABLE</isolation-level>
              with no significant change in behavior.
              In the ejb-jar.xml
              <container-transaction>
              <method>
              <ejb-name>ejb</ejb-name>
              <method-name>*</method-name>
              </method>
              <trans-attribute>Required</trans-attribute>
              </container-transaction>
              

              Try setting delay-updates-until-end-of-tx to false for your bean. Try experimenting
              with concurrency-strategy of Exclusive. Or re-write your code to not check for
              existence before creation; just create the bean and let the db return a duplicate
              key exception.
              simon.
              "Daniel" <[email protected]> wrote:
              >I seem to have a problem with a race-condition. Two threads are trying
              >to
              >create the same entity. One thread calls a finder with no success and
              >creates the entity, meanwhile - before the entity gets persisted
              >(ejbStore()) - the other thread also calls a finder with no success,
              >creating the
              >same entity.
              >
              >My transaction isolation level in the weblogic-ejb-jar.xml is
              ><transaction-isolation>
              ><isolation-level>TRANSACTION_READ_UNCOMMITTED</isolation-level>
              ><method>
              ><ejb-name>ejb</ejb-name>
              ><method-name>*</method-name>
              ></method>
              ></transaction-isolation>
              >
              >I've also tried <isolation-level>TRANSACTION_SERIALIZABLE</isolation-level>
              >with no significant change in behavior.
              >
              >In the ejb-jar.xml
              ><container-transaction>
              ><method>
              ><ejb-name>ejb</ejb-name>
              ><method-name>*</method-name>
              ></method>
              ><trans-attribute>Required</trans-attribute>
              ></container-transaction>
              >
              >
              

  • Two contexts sharing the same physical interface

    Hi,
    I have been looking for a configuration guide on how to set up one physical trunked interface to be shared between two contexts.  I am sure I am just using the wrong search words but have as of yet been unable to find anything on this. Anyone able to provide a link please?
    Thanks           

    Hi,
    I have not linked (or have the need to) 3 Security Contexts before but I would imagine you could modify the above configuration a bit to achieve that also
    interface GigabitEthernet0/0
    description TRUNK
    interface GigabitEthernet0/0.100
    description SC1 - OUTSIDE
    vlan 100
    interface GigabitEthernet0/0.200
    description SC2 - OUTSIDE
    vlan 200
    interface GigabitEthernet0/0.10
    description SC1 - INSIDE
    vlan 10
    interface GigabitEthernet0/0.20
    description SC2 - INSIDE
    vlan 20
    interface GigabitEthernet0/0.12
    description SC1 - TRANSIT
    vlan 12
    interface GigabitEthernet0/0.21
    description SC2 - TRANSIT
    vlan 21
    context TRANSIT
      description SC1 to SC2 TRANSIT SC
      allocate-interface GigabitEthernet0/0.12
      allocate-interface GigabitEthernet0/0.21
      config-url disk0:/TRANSIT.cfg
    context SC1
      description SC1
      allocate-interface GigabitEthernet0/0.100
      allocate-interface GigabitEthernet0/0.10
      allocate-interface GigabitEthernet0/0.12
      config-url disk0:/SC1.cfg
    context SC2
      description SC2
      allocate-interface GigabitEthernet0/0.200
      allocate-interface GigabitEthernet0/0.20
      allocate-interface GigabitEthernet0/0.21
      config-url disk0:/SC2.cfg
    I am not sure if this would be the way but that is how I imagined at the moment.
    The setup should look something like this
    Totally different matter would there be a better way to achieve the same as above
    - Jouni

  • Two computers sharing the same PC Music Library databa

    Is there any way two computers can share the same music library database? It's easy to share the mp3 files, but I want to share the database (which contains the playlists and smart playlists). I haven't been able to find a way to point the Organizer at a different database location (the default location is \Documents and Settings\{username}\Application Data\Creative\Media Database.
    Thanks,
    Jeff

    No, you cannot share the PC Music Library database. What you can do is that you can backup the PC Music Library database from the "master" PC and then bring the backup to the other PC and restore it to the other PC. You can perform the backup and restore in MediaSource's Tools->Settings->PC Music Library.

  • How to start two threads at the same time

    Hi there,
      I want to include multithreading in the CVI program. I have two tasks which has no dependence between them, so I would like to start two threads for perform the tasks. I follow the introduction http://www.ni.com/white-paper/3663/en/ to start my code. In my code, I add a command button, when it is pressed, I create two threads to perform the tasks. In each task, I have a big loop and in each iteration, I use ProcessSystemEvents to avoid no response on system message. But it doesn't work actually, the program suspended. I wonder must I initialize the threads in main. I am looking for a way to start the threads in the callback function for a button since I am not starting those threads at the beginning but while it is triggered.
    the main frame of the code looks
    int CVICALLBACK Test1(void *functionData)
    { int i=0;
    for (i = 0; i<100000; i++) {ProcessSystemEvents();}
    return 0;
    int CVICALLBACK Test2(void *functionData)
    int i = 0;
    for (i = 0; i<100000; i++) {ProcessSystemEvents();}
    return 0;
    int CVICALLBACK cmdcb(int panel, int control, int event, void *callbackData, int eventData1, int eventData2)
    { int threadID1, threadID2;
    if (event==EVENT_COMMIT)
    SetPanelAttribute(panelHandle, ATTR_DIMMED, 1);
    CmtScheduleThreadPoolFunction(DEFAULT_THREAD_POOL_HANDLE, Test1, NULL, &threadID1);
    CmtScheduleThreadPoolFunction(DEFAULT_THREAD_POOL_HANDLE, Test2, NULL, &threadID2);
    CmtWaitForThreadPoolFunctionCompletion (DEFAULT_THREAD_POOL_HANDLE, threadID1, 0);
    CmtWaitForThreadPoolFunctionCompletion (DEFAULT_THREAD_POOL_HANDLE, threadID2, 0);
    return 0;
    Attachments:
    TestThread.zip ‏239 KB

    In my opinion your threads may be simply lasting longer than expected due to an incorrect sleep policy of threads paired with with ProcessSystemEvents () in the loop.
    I made up a quick example that shows this behaviour: playing with "Do not sleep" and "Call ProcessSystemEvents" options you can see how threads execute.
    BTW: do not forget to release the thread function IDs at the end of functions.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?
    Attachments:
    thread.zip ‏7 KB

  • I have two iphones sharing the same e-mail and if one deletes an incoming email, it is deleted from the other iphone.  How can I stop that?

    I have two Iphones that share the same email.  we got new 4s phones.  Now if one person checks/deletes email, it does not show up on the other phone
    and it is taken off the server.
    How can I fix that?
    I want it to go to both phones and to remain on the server even if I delete it off my phone.
    Thanks

    You must be using a POP3 account like verizon.net
    using IMAP like gmail will help some of your problem, not all...
    even on IMAP accounts once one person checks the email it will not show as a "new" message anymore... and if deleted it will still be gone from both phones...
    There are settings you can change in the advanced section of the IMAP account settings that designate the phone NOT to delete messages at all as well... thought this is also an option on POP3 account settings too.

  • TS1474 Two iPhones sharing the same iTunes account - how do we create a new account for one of them now that both phones have been registered with the same account?

    We have recently upgraded 2 iPhones to the 4S and are having difficulties registering with the same log in and passwords in iTunes. 
    How can we re-register one of them with it's own identity and avoid the same apps being copied o both devices?
    We would like each iPhone to have it's own identity but use the same computer for backing up.

    Hi, you will need to set up a new user account on the computer. The iTunes on this new user will be empty but you can download past iTunes purchases from the iTunes store

  • Address Book - two users sharing the same address book

    My wife and I have separate accounts on the same mac. How can she share access to my address book. I tried to copy it over to a new directory in the same path ie, users>name>library>applicationsupport>addressbook - but this didn't work and caused the dreaded spinning icon.

    Checkout the macosxhints.com article "Share one Address Book among multiple users".

  • PFCG, two roles with the same object but different values

    Hi, Can you help me?
    I need to know if it's possible have two roles like this:
    role A - Object werks = L001 and LIKP-LFART = LF
    role B - Object werks = L005 and LIKP-LFART = ZLF
    If the some user have role A and role B it's possible that he doesn't have authorization for werks = L005 and LIKP-LFART LF?
    Thanks
    Dora

    I guess you made fat figure on the words: "it's possible that he doesn't have authorization for werks = L005 and LIKP-LFART ZLF", right?
    If so, it is impossible.
    When SAP doing the authorization check, it call the function "authority_check", input the Object, the filed and the value to check.
    if some one have role A and B, SAP will check authority both in Role A and Role B.
    What you need to do should be separating the Object into a subrole and assign it separately.
    >
    Jorge Sousa wrote:
    > Hi, Can you help me?
    > I need to know if it's possible have two roles like this:
    > role A - Object werks = L001 and LIKP-LFART = LF
    > role B - Object werks = L005 and LIKP-LFART = ZLF
    > If the some user have role A and role B it's possible that he doesn't have authorization for werks = L005 and LIKP-LFART LF?
    >
    > Thanks
    >
    > Dora

  • Aperture in two machines sharing the same library... possible?

    I want to have one library which I could share between two machines (Ive got an iMac and a MBP). But I'd like to keep the library in iMac and access it on MBP over the network. I don't need use it simultaneously, but I don't want to use an external drive for it either... Any ideas? Thanks

    Ian, and others,
    I am maintaining multiple boot volumes on my Mac Pro, with the primary ones being one for Tiger and one for Leopard. At the moment I am separately maintaining Photoshop CS3 and Final Cut Studio on each of those. I have recently installed Aperture on that Leopard boot. I now plan to establish another Leopard boot (using a WD 750 GB drive), primarily for the pro apps such as PS CS3, Aperture and Final Cut Studio 2 (an upgrade) while maintaining FCS 1 on the other boot drive. With FCP, the projects and voluminous files are of course maintained on drives other than the boot volumes, and thus FCP, for example, can use those files whether I am in the Tiger boot, or the Leopard boot.
    I have been wanting to fire up Aperture while in the Tiger boot, to test some odd printing behavior, but don't want to create another Aperture Library (which is not yet populated to any real extent) just to do the test. Also, I would like to administer the Aperture Library from the planned new Leopard boot, but not create separate libraries if I should wish to use Aperture while in other boot volumes.
    It seems clear (but I could be wrong) that this can be done, but is it advisable? Practical? Obviously, with the separate boots, I would never be using Aperture from but one "computer".
    Ernie

  • Two phones sharing the same apple Id. If I delete a photo from photo steam will it delete it from photo stream ?

    I recently bought a iPhone 5. I keep the old iPhone for my son to play games on over wifi. I signed out of my apple I'd but not my iCloud because it says if I turn it off the photos will be deleted. I do not want to lose the photos on either phone. I was wondering if it delete the iCloud account on the old phone will the photos on the old phone still be on there.

    Elizabethj221 wrote:
    ....... I was wondering if it delete the iCloud account on the old phone will the photos on the old phone still be on there.
    Yes.

  • Vector clone references the same objects??

    Hi all
    I'm developing a simple chess program.
    Obviously, each move the user tries must be checked against the following sets of chess rules:
    1.) Whether it is that colour player's turn to move
    2.) Whether this move is valid for this specific piece (eg. 3 forward for a King --> invalid of course)
    3.) Whether this move will jeopardize the player's king (put it in check)
    If from any of the above the move is found to be invalid, the move is not executed.
    My program structure is briefly this:
    A. abstract super class 'ChessPiece' - subclassed by the various specific Chess Piece classes.
    Each of the specific ChessPiece subclasses must implement an abstract method to check if a
    proposed move is valid, and also a method to actually do the move...
    B. 'PieceManager' class - has a Vector of ChessPieces:
    This class checks whether the given move is valid:
    For the piece: by calling the checking method (see A above)
    For the general game: by making sure the given move doesn't put the player's king in check.
    NOTE: In chess (for those who don't know), it is illegal to move any piece if, at the end of
    the move, your king will be in check [possible to be captured by any enemy piece]
    This last check I want to do in the following way:
    1) copy/clone the entire PieceManager object
    2) in this copied object, actually do the move
    3) still in the copied/cloned object, see if the moving player's king is now in check
    4) based on this evaluation, execute the move in the original PieceManger object or don't...
    The Problem:
    When I clone this PieceManager object, its 'pieces' Vector is obviously also cloned.
    BUT it seems that the cloned 'pieces' Vector references the same ChessPiece objects
    as those referenced by the original 'pieces' Vector; ie the 2 Vectors are sharing the same Objects.
    Thus, when I actually execute the move in the test/cloned PieceManager object,
    the original PieceManager's corresponding piece is moved too (well, it seems it is the same piece...).
    I am pretty stuck with this.
    I've tried the Vector clone method; it doesn't seem to copy the objects, but create another reference
    to the same objects, as I've said.
    I've tried cloning the entire object ; also not helping......
    I'd love any comments, helpful pointers, suggestions.
    Also any comments on my program structure... is a Vector the best tool for this job?
    Thanks very much -
    lutha

    Hi all, OP here.
    Ok thanks guys for all your posts...
    two points:
    1) I have tried the "copy constructor", and it seems to be doing the same thing. (ie 'shallow clone')
    What's really frustrating me is that nothing I do seems to actually physically copy the Vector's objects
    to new, separate copies of those objects...
    I had my PieceManager class implement Cloneable (just in case - not too sure on that one; in fact I
    commented that out later), and I overrode the clone method like this:
    public Object clone ()
            PieceManager pm = new PieceManager ();
            Vector pcs = new Vector ();
            // Enumeration e = pieces.elements ();
            //while (e.hasMoreElements ())
            //    ChessPiece p = (ChessPiece) e.nextElement ();
            //pcs.add ();
            //}  // still references the same objects!!
            pieces.trimToSize ();
            int size = pieces.size ();
            Object[] arr = new Object [size];
            Object[] initial = pieces.toArray ();
            System.arraycopy (initial, 0, arr, 0, size);
            for (int i = 0 ; i < size ; i++)
                ChessPiece p = (ChessPiece) arr ;
    pcs.add (p);
    pm.pieces = pcs;
    return pm;
    This all still does the same 'shallow cloning'...
    2) m.winter, my ChessPiece objects are not immutable - they have a co-ordinate field that
    changes as they are moved. This is for getting as called by another object, and for checking in
    the ChessPiece's own internal method for checking whether the passed-in square co-ordinate
    is a valid destination.
    Anyway, I don't think that's the main issue here. How can I properly clone/copy a Vector, resulting
    in :
    a) the original Vector
    b) a new, totally unrelated Vector.
    Thanks again all for your input.
    regards,
    lutha

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Maybe you are looking for