Results 1 to 17 of 17

Thread: What does the "synchronized" keyword for?

  1. #1

    Thread Starter
    Banned debbie_82's Avatar
    Join Date
    Jan 2004
    Location
    inside a hollow void
    Posts
    104

    What does the "synchronized" keyword for?

    Can anyone explain to me what the synchronized keyword is for in java...

  2. #2
    Addicted Member MethadoneBoy's Avatar
    Join Date
    Oct 2001
    Location
    Preferably somewhere between Keira Knightley and Diane Kruger but I'm not fussy
    Posts
    180
    Sure thing

    Synchronized is used to control access to a method by other classes so that the method can only be used by one class at a time and no class can call the method until it has carried out its function.

    It's a pretty vital part of Java programming, especially when it comes to using multiple threads in your program.

    Example:

    Say we have a method getAmount () which is NOT synchronized and returns the integer value 5. We also have three classes : A, B, C. The method getAmount() is contained in class C.

    Class A wants to get the amount in class C, so it calls the getAmount method. Now, while this is happening, class C changes the amount from 5 to 7. This change occurs while A is calling getAmount. At the same time, class B also calls getAmount. The result is that, because the method is not synchronized, A and B will recieve the value 5 from getAmount. This is a problem because C changed to value from 5 to 7 after A called the method and ideally, the two classes should recieve the most up-to-date information available.

    Now say we make getAmount synchronized and start over. A calls the method. Then C tries to change the value in getAmount. C will be prevented from doing this because the synchroznized keyword will "lock" the method until A has finished with it. After A has finished, C changes the value. While C is changing the value, B tries to call getAmount. B will be prevented from doing this because of the same "lock" that stopped C. As a result, C will finish updating the method and B will get the value 7 from getAmount.

    Sorry about the length of that reply, I hope it wasn't too confusing

    Hope that helps!
    "'Oh, hello Mr. Crick! What do you think of Jeffrey Archer?' Clip-clip-clip! Oh, come on! Who are you kidding? You wait til I'm mayor, you'll see how tough I am! Christ almighty...."

  3. #3
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418
    There is usually a big penalty when using synchronization which comes in the form of a performance hit. For instance using a Vector(which has many of it's methods synchronized) can slow your code down by a large factor. This is exactly why classes such as java.util.Vector and HashTable are now referred to as legacy code. The API has been reworked with all of the collection API's being unsynchronized.

    Synchronization can still be added to a collection using various static methods on the Collection class but that would be getting off topic. Point is that using synchronization is not always the best choice.

  4. #4
    Fanatic Member
    Join Date
    Dec 2003
    Posts
    703
    Locks aren't particularly expensive unless you have reasonable contention. The 1.5 SDK introduces atomic ops, which in turn introduces the possibility of "lock-free" data structures.
    an ending

  5. #5

    Thread Starter
    Banned debbie_82's Avatar
    Join Date
    Jan 2004
    Location
    inside a hollow void
    Posts
    104
    Originally posted by MethadoneBoy
    Sure thing

    Synchronized is used to control access to a method by other classes so that the method can only be used by one class at a time and no class can call the method until it has carried out its function.

    It's a pretty vital part of Java programming, especially when it comes to using multiple threads in your program.

    Example:

    Say we have a method getAmount () which is NOT synchronized and returns the integer value 5. We also have three classes : A, B, C. The method getAmount() is contained in class C.

    Class A wants to get the amount in class C, so it calls the getAmount method. Now, while this is happening, class C changes the amount from 5 to 7. This change occurs while A is calling getAmount. At the same time, class B also calls getAmount. The result is that, because the method is not synchronized, A and B will recieve the value 5 from getAmount. This is a problem because C changed to value from 5 to 7 after A called the method and ideally, the two classes should recieve the most up-to-date information available.

    Now say we make getAmount synchronized and start over. A calls the method. Then C tries to change the value in getAmount. C will be prevented from doing this because the synchroznized keyword will "lock" the method until A has finished with it. After A has finished, C changes the value. While C is changing the value, B tries to call getAmount. B will be prevented from doing this because of the same "lock" that stopped C. As a result, C will finish updating the method and B will get the value 7 from getAmount.

    Sorry about the length of that reply, I hope it wasn't too confusing

    Hope that helps!
    Hey tnx...no prob on the lengthy reply... ...

  6. #6

    Thread Starter
    Banned debbie_82's Avatar
    Join Date
    Jan 2004
    Location
    inside a hollow void
    Posts
    104
    Originally posted by Dilenger4
    There is usually a big penalty when using synchronization which comes in the form of a performance hit. For instance using a Vector(which has many of it's methods synchronized) can slow your code down by a large factor. This is exactly why classes such as java.util.Vector and HashTable are now referred to as legacy code. The API has been reworked with all of the collection API's being unsynchronized.

    Synchronization can still be added to a collection using various static methods on the Collection class but that would be getting off topic. Point is that using synchronization is not always the best choice.

    You mean it's not always good to use Vector and HashTable?... We'll I've been using a lot of Vectors in my code... I'm using jdk1.4 ... is the Vector collection for this version being reworked to become unsynchronized? I don't know much about the inner workings of java and I'm also a newbie so pls bear with me.

  7. #7

    Thread Starter
    Banned debbie_82's Avatar
    Join Date
    Jan 2004
    Location
    inside a hollow void
    Posts
    104
    Originally posted by azteched
    Locks aren't particularly expensive unless you have reasonable contention. The 1.5 SDK introduces atomic ops, which in turn introduces the possibility of "lock-free" data structures.
    What are atomic ops?

  8. #8
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418
    Yes all of the collections API's have been reworked to be unsynchronized. Special synchronized wrappes have been implemented and hidden from us for creating polymorphic, thread-safe implementations of the unsynchronized classes.

  9. #9
    Fanatic Member
    Join Date
    Dec 2003
    Posts
    703
    Originally posted by debbie_82
    What are atomic ops?
    Operations that are, or appear to be, indivisible with respect to your code, e.g. incrementing a value, or putting the value of one bit of memory into another. This means you can safely update the same memory from multiple threads concurrently, without using locks. Fundamentally, the "atomic" functions will probably use special atomic instructions provided by the CPU.

    The Win 32 API has atomic ops:

    InterlockedIncrement/Decrement
    InterlockedExchange/CompareExchange
    etc.
    an ending

  10. #10

    Thread Starter
    Banned debbie_82's Avatar
    Join Date
    Jan 2004
    Location
    inside a hollow void
    Posts
    104
    tnx i'm enlightened...

  11. #11
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    Methadone Boy's long post is not entirely correct. Synchronization doesn't have anything to do with classes, just with threads. No more than one thread can call a synchronized function or execute a synchronized block at any time, the other threads have to wait.

    So the example needs to be rewritten.

    Let's assume that a class contains a method doFancyThing, and another method setInterestingValue, which sets a member variable of the class.
    doFancyThing uses this variable, and it uses it twice. Once at the start of the function, again near the end.

    Let's further assume we have two threads, A and B. Threads run, for all intents and purposes, at the same time. Now A calls doFancyThing. doFancyThing accesses the variable the first time.
    In the meantime, B calls setInterestingValue and changes this variable. As a result the second access of the variable yields a different value than the first. This may lead to unpredictable results, doFancyThing might rely on the two accesses to yield the same value. And here's where synchronized comes in.

    By making both methods synchronized, B cannot call setInterestingValue while A is executing doFancyThing, it has to wait for A to finish. This ensures that the variable is not changed during the execution of doFancyThing and all is well.



    The collections API. Instead of Vector use ArrayList, instead of HashTable use HashMap. The new are unsynchronized and follow the Java collection framework, which makes them useful in other ways too.
    With Java 1.5, you can use StringBuilder instead of StringBuffer. Again, StringBuilder is unsynchronized and thus considerably faster. You can notice this when you concatenate strings and other stuff, because now the compiler uses StringBuilder to do this instead of StringBuffer.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  12. #12
    Addicted Member MethadoneBoy's Avatar
    Join Date
    Oct 2001
    Location
    Preferably somewhere between Keira Knightley and Diane Kruger but I'm not fussy
    Posts
    180
    Originally posted by CornedBee
    Methadone Boy's long post is not entirely correct. Synchronization doesn't have anything to do with classes, just with threads. No more than one thread can call a synchronized function or execute a synchronized block at any time, the other threads have to wait.
    Apologies, I should have made that clearer. I did actually mean that Class A and Class B are both Thread classes and Class C is a monitor object being shared by both.
    "'Oh, hello Mr. Crick! What do you think of Jeffrey Archer?' Clip-clip-clip! Oh, come on! Who are you kidding? You wait til I'm mayor, you'll see how tough I am! Christ almighty...."

  13. #13
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418
    According to sun whenever control enters a synchronized method, the thread that called the method locks the object whose method has been called. Other threads cannot call a synchronized method on the same object until the object is unlocked. From what i remember there is a difference between static methods that are marked synchronized and non-static methods marked synchronized in regard to what the thread that invoked either of these methods locks.

  14. #14
    Fanatic Member
    Join Date
    Dec 2003
    Posts
    703
    I would think the caller of a static method wouldn't lock a mutex associated with the object, but a separate one associated with that specific method.
    an ending

  15. #15

    Thread Starter
    Banned debbie_82's Avatar
    Join Date
    Jan 2004
    Location
    inside a hollow void
    Posts
    104
    Originally posted by CornedBee
    Methadone Boy's long post is not entirely correct. Synchronization doesn't have anything to do with classes, just with threads. No more than one thread can call a synchronized function or execute a synchronized block at any time, the other threads have to wait.

    So the example needs to be rewritten.

    Let's assume that a class contains a method doFancyThing, and another method setInterestingValue, which sets a member variable of the class.
    doFancyThing uses this variable, and it uses it twice. Once at the start of the function, again near the end.

    Let's further assume we have two threads, A and B. Threads run, for all intents and purposes, at the same time. Now A calls doFancyThing. doFancyThing accesses the variable the first time.
    In the meantime, B calls setInterestingValue and changes this variable. As a result the second access of the variable yields a different value than the first. This may lead to unpredictable results, doFancyThing might rely on the two accesses to yield the same value. And here's where synchronized comes in.

    By making both methods synchronized, B cannot call setInterestingValue while A is executing doFancyThing, it has to wait for A to finish. This ensures that the variable is not changed during the execution of doFancyThing and all is well.



    The collections API. Instead of Vector use ArrayList, instead of HashTable use HashMap. The new are unsynchronized and follow the Java collection framework, which makes them useful in other ways too.
    With Java 1.5, you can use StringBuilder instead of StringBuffer. Again, StringBuilder is unsynchronized and thus considerably faster. You can notice this when you concatenate strings and other stuff, because now the compiler uses StringBuilder to do this instead of StringBuffer.
    Since you've mentioned HashMap... I haven't used HashMap and the project assigned to me is about HashMap can you give me an address regarding HashMaps? . I find it cumbersome to look it up in the API... tnx... 'cause some real code will do...

  16. #16
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    Huh? I always use my local javadoc for reference...

    But the API reference at java.sun.com should be enough. The usage is nearly the same as for HashTable.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  17. #17
    Addicted Member MethadoneBoy's Avatar
    Join Date
    Oct 2001
    Location
    Preferably somewhere between Keira Knightley and Diane Kruger but I'm not fussy
    Posts
    180
    Originally posted by debbie_82
    'cause some real code will do...
    This is taken from the net. Just put "HashMap Java" into google and check the results.

    Code:
    import java.util.*;
    
    class Test {
    
    static  public void main(String args[]) {
    
        HashMap h1=new HashMap();
        HashMap h2=new HashMap();
    
        h1.put(new Integer(1), new Integer(2));
        h2.put(new Boolean(true), new Boolean(false));
    
        for (Iterator i=h1.entrySet().iterator(); i.hasNext();) {
    
          Map.Entry entry=(Map.Entry)i.next();
          Integer l=(Integer)entry.getKey();
    
        }
    
        for (Iterator i=h2.entrySet().iterator(); i.hasNext();) {
    
          Map.Entry entry=(Map.Entry)i.next();
          Boolean l=(Boolean)entry.getKey();
    
        }
    
      }
    
    }
    What is your project about, incidentally?
    "'Oh, hello Mr. Crick! What do you think of Jeffrey Archer?' Clip-clip-clip! Oh, come on! Who are you kidding? You wait til I'm mayor, you'll see how tough I am! Christ almighty...."

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width