Results 1 to 2 of 2
- 09-08-2010, 02:19 PM #1
Member
- Join Date
- Sep 2010
- Posts
- 1
- Rep Power
- 0
Difference b/w "synchronized","synchronize",and "synchronized()"
Hi,
could anyone tell me the difference b/w "synchronized","synchronize",and "synchronized()" and where these could be applied?
Also pls tell me about synchronize block and synchronize method. It's bit confusing to me:confused:.
Thanks in advance,
Bala
- 09-08-2010, 04:08 PM #2
Senior Member
- Join Date
- Nov 2008
- Posts
- 286
- Rep Power
- 5
You use synchronized in multi-threaded programming. To put it simply, only one thread at a time is allowed "into" the synchronized block. So for example, we can create a counter object shared among multiple threads as follows:
A synchronized method looks as follows:Java Code:public class Counter { private int count = 0; public void increment() { synchronized (this) { count++; } } public int getCount() { synchronized (this) { return count; } } }
Making the method synchronized is essentially the same as saying "imagine that the entire code inside this method is written inside a synchronized block".Java Code:public synchronized void increment() { count++; }
I stole this example from some more detailed information I wrote about the Java synchronized keyword, but you'll find a lot about the topic on line.
When should you use a sychronized block? Essentially, when you have code that reads or writes data that is shared among multiple threads (and if you haven't put some other protection in place -- there are actually other methods to make data threadsafe).
Note that there are a few disadvantages of declaring the method synchronized which more advanced programmers will want to consider.Neil Coffey
Javamex - Java tutorials and performance info
Similar Threads
-
Java, Military Format using "/" and "%" Operator!!
By sk8rsam77 in forum New To JavaReplies: 11Last Post: 02-26-2010, 03:03 AM -
How to change my form design from "metal" to "nimbus" in Netbeans 6.7.1?
By mlibot in forum New To JavaReplies: 1Last Post: 01-21-2010, 09:20 AM -
problem with argument list and precedence "(" and ")"
By helpisontheway in forum Advanced JavaReplies: 6Last Post: 12-24-2009, 07:50 AM -
MoneyOut.println("It took you (whats wrong?>",year,"<WW?) years to repay the loan")
By soc86 in forum New To JavaReplies: 2Last Post: 01-24-2009, 06:56 PM -
the dollar sign "$", prints like any other normal char in java like "a" or "*" ?
By lse123 in forum New To JavaReplies: 1Last Post: 10-20-2008, 07:35 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks