Can anyone explain to me what the synchronized keyword is for in java... :)
Printable View
Can anyone explain to me what the synchronized keyword is for in java... :)
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 :o
Hope that helps! :wave:
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. :lol: Point is that using synchronization is not always the best choice.
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.
Hey tnx...no prob on the lengthy reply... :D...Quote:
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 :o
Hope that helps! :wave:
Quote:
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. :lol: 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.
What are atomic ops?Quote:
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.
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.
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.Quote:
Originally posted by debbie_82
What are atomic ops?
The Win 32 API has atomic ops:
InterlockedIncrement/Decrement
InterlockedExchange/CompareExchange
etc.
tnx i'm enlightened... :)
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.
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.Quote:
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.
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.
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.
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...Quote:
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.
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.
This is taken from the net. Just put "HashMap Java" into google and check the results.Quote:
Originally posted by debbie_82
'cause some real code will do...
What is your project about, incidentally?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();
}
}
}