Results 1 to 2 of 2
  1. #1
    Bala_Rugan is offline Member
    Join Date
    Sep 2010
    Posts
    1
    Rep Power
    0

    Cool 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

  2. #2
    neilcoffey is offline Senior Member
    Join Date
    Nov 2008
    Posts
    286
    Rep Power
    6

    Default

    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:

    Java Code:
    public class Counter {
      private int count = 0;
      public void increment() {
        synchronized (this) {
          count++;
        }
      }
      public int getCount() {
        synchronized (this) {
          return count;
        }
      }
    }
    A synchronized method looks as follows:

    Java Code:
    public synchronized void increment() {
      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".

    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.

Similar Threads

  1. Java, Military Format using "/" and "%" Operator!!
    By sk8rsam77 in forum New To Java
    Replies: 11
    Last Post: 02-26-2010, 03:03 AM
  2. Replies: 1
    Last Post: 01-21-2010, 09:20 AM
  3. problem with argument list and precedence "(" and ")"
    By helpisontheway in forum Advanced Java
    Replies: 6
    Last Post: 12-24-2009, 07:50 AM
  4. Replies: 2
    Last Post: 01-24-2009, 06:56 PM
  5. Replies: 1
    Last Post: 10-20-2008, 07:35 AM

Posting Permissions

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