Synchronized method / synchronized blocks

What is the difference between using the synchronized keyword to make a method synchronized and using synchronized blocks? The book that I have only offers a brief explanation of synchronized blocks that is semantically termed as, "a block that allows arbitrary code to be synchronized on the monitor of an arbitrary object."
Thanks in advance for any help.

Synchronizing an instance method is semantically equivanlent to synchronizing the entire body of that method on this.
Synchronizing a static method is semantically equivanlent to synchronizing the entire body of that method on the Class object representing the class that the method is defined in.
i.e., The following two classes are equivalent:
public class MyClass {
  public synchronized void instanceMethod() {
    //code...
  public static synchronized void staticMethod() {
    //code...
public class MyClass {
  public void instanceMethod() {
    synchronized (this) {
      //code...
  public static void staticMethod() {
    synchronized (MyClass.class) {
      //code...
}

Similar Messages

  • Differences between Synchronized methods and blocks

    Hi all,
    I would like to differences between Synchronized methods and blocks.
    - Muni

    Well, you'll get so many of right answers in next ten to thirty minutes.
    I like to yield :)
    Oooo... Ten minutes has passed.
    Synchronized block is a toilet room with a lock in a public lavatory.
    Only one person(running thread) can have the lock at a time.
    And, she/he have to receive the lock from a particular object obj like:
    synchronized(obj){.....} // one object has only one lock for this {} toilet and for any other toilets how many there are... *
    (*: In other words, while a thread is executing a synchronized(obj){} block, other threads can't enter other synchronized(obj){} blocks.)
    Synchronized method is a kind of synchronized block.
    This special block is defaulted to have lock from the object on which the method is defined.
    public class Foo{public synchronized Method(){}}
    use the lock of a Foo object.
    Message was edited by:
    hiwa
    Message was edited by:
    hiwa

  • Synchronized method's block list implementation

    In an object with synchronized methods, the OS maintains the list of blocked objects waiting to enter synchronzied methods. For this reason, I'm guesing, the Java spec seems to state the selection of these blocked objects as "arbitrary."
    I am trying to determine that there is no risk of stavation in this blocked pool of threads. For example, a FIFO implementation of the blocked-object list would guarantee that all objects eventually entered their appropriate synchronized method.
    Does anyone know for certain what blocked object selection algorithm is present on a JVM running on a Win32 platform? On SunOS 5.6? I believe the former uses a priority-based, preemptive thread scheduling with a round-robin-style time quantum to prevent starvation. Not sure what the latter uses.
    Any ideas? Thanks!
    -Jeff Ishaq

    In an object with synchronized methods, the OS
    maintains the list of blocked objects waiting to enter
    synchronzied methods. For this reason, I'm guesing,
    the Java spec seems to state the selection of these
    blocked objects as "arbitrary."
    As a general rule, you can never depend on the underlying threading model. The trend is to use the native threading model but that is not guaranteed by the specification.
    I am trying to determine that there is no risk of
    stavation in this blocked pool of threads. For
    example, a FIFO implementation of the blocked-object
    list would guarantee that all objects eventually
    entered their appropriate synchronized method.
    When a thread attempts to acquire a lock, it only checks to see if another thread already holds the lock, and not if another thread is already waiting for the lock. Therefore you should always consider the possibility that starvation can occur.
    Does anyone know for certain what blocked object
    selection algorithm is present on a JVM running on a
    Win32 platform? On SunOS 5.6? I believe the former
    uses a priority-based, preemptive thread scheduling
    with a round-robin-style time quantum to prevent
    starvation. Not sure what the latter uses.
    Again, you should avoid depending on the native threading model because the specification does not guarantee that the java threading model is going to behave the same way.
    To guarantee that each thread can acquire the lock you will need to develop a lock that has a queue associated with it. When a thread attempts to acquire the lock it is placed in a queue waiting until it is the first element in the queue. When the thread releases the lock it removes itself from the queue and notifies the other threads that are waiting.
    When using a queued lock you will not necessarily need to use the synchronized keyword on the method or block since the lock will take care of synchronization when a thread attempts to acquire the lock.

  • Which object's monitor does a synchronized method acquire?

    from the Java Tutorial for concurrency programming:
    " When a thread invokes a synchronized method, it automatically acquires the intrinsic lock _for that method's object_ and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception. "
    what exactly does this mean?
    do synchronized methods acquire the monitors for objects of type: java.lang.reflection.Method
    please consider this code:
    public class Foo {
      private int counter = 0;
      public synchronized void incriment() { counter++; }
      public synchronized void decriment() { counter--; }
    Foo f = new Foo();
    Class[] sig = new Class[0];
    Method m = f.getClass().getMethod("incriment", sig);
    // ok. so "m" is the relevant method object.
    f.incriment(); // <-- is the monitor for "m" ,
                          // or the monitor for "f", acquired?
    .......my reading of the Concurrency Tutorial is that synchronized methods use the monitors of java.lang.reflection.Method objects?
    and thus, Foo is not thread safe, right?
    however, this simple change makes Foo thread-safe?
    public class Foo {
      private volatile int counter = 0; // "volatile"
      public void incriment() { counter++; }
      public void decriment() { counter--; }
    }thanks.
    Edited by: kogose on Feb 23, 2009 7:13 PM

    tensorfield wrote:
    jverd wrote:
    tensorfield wrote:
    kogose wrote:
    what exactly does this mean?It means you're complicating things.
    If a method is synchronized, it is. You don't need to go beyond that. The method is synchronized.Not true. You have to know what it means for a method to be synchronized. Often people come in with the erroneous impression that it somehow prevents you from using or accessing the object in any other thread.It's very simple. If a synchronized method is called at the same time from many threads only one call will be executed at a time. The calls will be lined up and performed one after the other in sequence.
    AND because synchronization is on a per object basis, when one synchronized method is being called from one thread, all synchronized methods of that same object are blocked for calling from other threads.
    Simple as that.No, it's not that simple, and as stated, that is not correct. In particular, you didn't mention that for an instance method, all the various threads have to be trying to call instance methods on the same object in order for execution to be sequential.
    You really can't understand Java's syncing without understanding how it relates to locks, and what it means for a method to be synchronized in terms of which lock it acquires.
    Edited by: jverd on Feb 25, 2009 2:47 PM

  • Synchronized method in a java class used by many interfaces

    My interface (idoc to file) is using a java class, which has one method that reads a table from a central database and after doing some calculations updates it.
    (The interface instantiate the class inside a user-defined function and calls the method there.)
    The problem is that if somebody sends 100 idocs at the same time, there can be a “dirty read”, I mean, a read just before other interface updates the table.
    We want the following:
    Interface 1:
    -          Read counter from the table (counter = 5 )
    -          Increment counter (counter = 6)
    -          Update table with that counter (table with counter = 6)
    Interface 2:
    -          Read counter from the table (counter = 6 )
    -          Increment counter (counter = 7)
    -          Update table with that counter (table with counter = 7)
    RESULT: The table has the counter = 7
    But what is happening is the following:
    -          Interface 1 reads (counter = 5)
    -          Interface 2 reads (counter = 5)
    -          Interface 1 increments counter (counter = 6)
    -          Interface 2 increments counter (counter = 6)
    -          Interface 1 updates table (table with counter = 6)
    -          Interface 2 updates table (table with counter = 6)
    RESULT: The table has the counter = 6 (WRONG)
    I made the method synchronized. What I was expecting was that only one interface (i1) could enter the method (read the table and update it) while other interfaces running at the same time would have to wait until i1 finished that method.
    My first test indicates that's not happening. Can anybody help me to find a solution?

    Hi Bhavesh,
    If the QOS is EOIO this means that the integration engine manage the call to the mapping program (and all the other blocks) inside an "internal" synchronized method.
    So this means that in this case you do not need to manage the queued access (synchronization) inside your custom java code because it is already enveloped in a queued block by XI.
    The problem that Jorge had can be easily reproduced using the sample code that follows:
    <b>class Synch Object</b>
    import java.util.Date;
    public class SynchObject {
         String strName;
         public SynchObject(String strName){
              this.strName = strName;
         public synchronized void syncWrite(String strCaller) throws InterruptedException{
              Date now;
              now = new Date();
              System.out.println("-- " + now.toLocaleString() + " " + strCaller + " entering syncWrite of " + strName);
              System.out.flush();
              Thread.sleep(1000);
              now = new Date();
              System.out.println("-- " + now.toLocaleString() + " syncWrite of " + strName + " called by " + strCaller );
              System.out.flush();
              Thread.sleep(1000);
              now = new Date();
              System.out.println("-- " + now.toLocaleString() + " " + strCaller + " leaving syncWrite of " + strName);
              System.out.println("");
              System.out.flush();
    <b>class Caller</b>
    public class Caller implements Runnable {
         String strName;
         SynchObject target;
         int intMax;
         public Caller(String strName, SynchObject target, int intMax) {
              this.strName = strName;
              this.target = target;
              this.intMax = intMax;
         public void run() {
              for(int i=0; i<intMax;i++)
                   try {
                        target.syncWrite(strName);
                   } catch (InterruptedException e) {
                        e.printStackTrace();
    <b>class Workbench</b>
    public class Workbench {
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              SynchObject sObj1 = new SynchObject("syncObj1");
              SynchObject sObj2 = new SynchObject("syncObj2");
              Caller c1 = new Caller("caller1",sObj1,2);
              Caller c2 = new Caller("caller2",sObj1,2); '[*CHANGE*]
              Thread ct1 = new Thread(c1);
              Thread ct2 = new Thread(c2);
              ct1.start();
              ct2.start();
    Run the workbench class to see what happen when setting QOS EOIO (the synch object is the same).
    To see instead what happen now (missing synchronization) you have to change in Workbench class the statement
    Caller c2 = new Caller("caller2",sObj1,2); '[*CHANGE*]
    with
    Caller c2 = new Caller("caller2",sObj2,2); '[*CHANGE*]
    The reason is that every instance of the mapping program declare a new instance of the "Synchronized object" so the calls are synchronized inside the same mapping program but not between several mapping program.
    Hope this give you a better idea on this problems with java synchronization, but if you have further doubts (I know it's a little bit tricky ) feel free to ask.
    Kind Regards,
    Sergio

  • What is a lock in a synchronized method ??

    Greetings,
    I have a synchronized reset method whose job is to reset every variable i am using in that class.. its a synchronized method so when i am doing the reset stuff, no other method in that class can update that variable. But someone told me i need to also put lock inside the reset method and check for the lock everywhere where i update those variables ( So that variable doesn't update itself and lose its value as reset would be resetting that variable.) How do i lock all these variables in that reset method and how do i check for the lock where i would be updating that variable.
    Example: Psedo code
    class {
    int a =0;
    int b = 0;
    method update {
    a = 5;
    method update1{
    b = 6;
    synchronized method reset{
    a =0;
    b = 0;

    javanewbie83 wrote:
    Greetings,
    I have a synchronized reset method whose job is to reset every variable i am using in that class.. its a synchronized method so when i am doing the reset stuff, no other method in that class can update that variable. But someone told me i need to also put lock inside the reset method and check for the lock everywhere where i update those variables ( So that variable doesn't update itself and lose its value as reset would be resetting that variable.) How do i lock all these variables in that reset method and how do i check for the lock where i would be updating that variable.You don't need to "check" for the lock. When you have a synchronized block or method, the synhcronized keyword tells the VM to stop executing that thread until it can attain the object's lock, then give the object's lock to that thread, and then take it back when the thread leaves the synchronized block (or calls wait()). It's all automatic.
    Note that you'll need to synchronize not only write access to the variable(s) in question, but read access also, in order to ensure that reader threads see the values written by writers.

  • Multiple static synchronized methods locking the same object ?

    If I have multiple static synchronized methods in a class will all the methods lock on the same (Class) object ? I guess the answer to this would be yes. In that case is it possible achieve synchronization without an object ie code level synchronization ? If yes, how ?

    If I have multiple static synchronized methods in a
    class will all the methods lock on the same (Class)
    object ? I guess the answer to this would be yes. In
    that case is it possible achieve synchronization
    without an object ie code level synchronization ? If
    yes, how ?There is nothing special about static synchronized methods vs. any other synchronization. It's just shorthand for syncing on the Class object for that class. The effects of synchronization are identical no matter what you sync on.
    There's no way to achieve synchronization without an object. Synchronizing always obtains an object's lock. In the case of static synced methods, the object whose lock we obtain is the Class object for that class. As far as syncing goes, it's just another object.
    There is no such thing as "code level synchronization" vs. any other kind. All syncing occurs in your Java code over blocks of code. For synced methods, those blocks are the entire respective method bodies.
    Having said all that, I have no idea what you're really after or what you're trying to achieve.

  • Static synchronized methods

    Hi
    Why dont we declare static methods synchronized especially if they are doing some complex calculation on some passed arguments ?
    thanks
    ali

    lucky_ali80 wrote:
    Hi guys
    Thanks for your quick replies. But i am still a bit confused.Then you're making it more complicated than it is.
    You synchronize a block of code when you want to makes sure only one thread at a time can obtain a given lock for that block of code. You declare an instance (non-static) method synchronized as a shorthand for synchronizing the block that is its body on this, and you declare a class (static) method synchronized as a shorthand for synchronizing its body on the Class object for that class.
    >
    For e.g my static function looks some thing like the one below:
    public class MyClass
    public static int computeSomething ( int a , int b)
    // a number of lines of complex computation on a and b
    return result.
    Now Say its a webserver running with object1, object2, 3...10 of the same type being maintained by the server. (Not threads but objects)
    say all these objects simultaneously call my static function with their respective arguments.
    Would this cause any synchronization issues??No. As I said in my first reply, every thread has its own copy of local variables. This includes method parameters. Each thread has its own a and b here.
    Now, if you're using some other data besides a and b, and if that data is shared among multiple threads, then you may have an issue. We can't say for sure because there are many different possible scenarios.
    Edited by: jverd on Feb 10, 2009 11:58 AM

  • Range of synchronized method?

    Hi,
    If you have a synchronized method, which calls another method, is that other method also synchronized?
    protected synchronized void doSomething() {
        // ... some coding
        heavyNumberCrunching()
        // ... some more coding
    protected void heavyNumberCrunching() {
        // ... even more coding
    }Additions:
    1. only doSomething() calls heavyNumberCrunching()
    2. heavyNumberCrunching() reads from/writes to collections, that can be accessed by other thread. Will access to these collections (not necessarily a Vector or Hashtable) be restricted when heavyNumberCrunching is crunching away?
    Just wondering.
    Abel

    spoon_ wrote:
    Abel wrote:
    If you have a synchronized method, which calls another method, is that other method also synchronized?yes, This is incorrect.
    the lock is held from when the method begins to when it endsWhile it is true that the lock is held until the synchronized method ends, that lock does not prevent access to unsynchronized methods by other threads.
    An example:
    =============
    public class Crunch {
        Crunch() {
            Thread[] aTeam = new Thread[10];
            for (int i = 0; i < 10; i++) {
                aTeam[i] = new Thread(new Runnable() {
                    public void run() {
                        doSomething();
                }, "A Team Thread " + i);
                aTeam.start();
    Thread[] bTeam = new Thread[10];
    for (int i = 0; i < 10; i++) {
    bTeam[i] = new Thread(new Runnable() {
    public void run() {
    heavyNumberCrunching();
    }, "B Team Thread " + i);
    bTeam[i].start();
    public synchronized void doSomething() {
    heavyNumberCrunching();
    public void heavyNumberCrunching() {
    System.out.println("Crunching on thread: " + Thread.currentThread().getName());
    try {
    Thread.sleep(2000);
    } catch (InterruptedException ie) {
    ie.printStackTrace();
    System.out.println("Done crunching on thread: " + Thread.currentThread().getName());
    public static void main(String[] args) {
    new Crunch();
    The A Team threads all access the heavyNumberCrunching() method via the synchronized doSomething() method. The B Team threads call heavyNumberCrunching() directly.
    Here's some output from a run on my quad core machine:
    Crunching on thread: A Team Thread 0
    Crunching on thread: B Team Thread 0
    Crunching on thread: B Team Thread 1
    Crunching on thread: B Team Thread 2
    Crunching on thread: B Team Thread 3
    Crunching on thread: B Team Thread 4
    Crunching on thread: B Team Thread 5
    Crunching on thread: B Team Thread 6
    Crunching on thread: B Team Thread 7
    Crunching on thread: B Team Thread 9
    Crunching on thread: B Team Thread 8
    Done crunching on thread: B Team Thread 5
    Done crunching on thread: B Team Thread 4
    Done crunching on thread: B Team Thread 9
    Done crunching on thread: B Team Thread 3
    Done crunching on thread: B Team Thread 7
    Done crunching on thread: B Team Thread 1
    Done crunching on thread: B Team Thread 2
    Done crunching on thread: A Team Thread 0
    Done crunching on thread: B Team Thread 8
    Done crunching on thread: B Team Thread 6
    Done crunching on thread: B Team Thread 0
    Crunching on thread: A Team Thread 9
    Done crunching on thread: A Team Thread 9
    Crunching on thread: A Team Thread 8
    Done crunching on thread: A Team Thread 8
    Crunching on thread: A Team Thread 7
    Done crunching on thread: A Team Thread 7
    Crunching on thread: A Team Thread 6
    Done crunching on thread: A Team Thread 6
    Crunching on thread: A Team Thread 5
    Done crunching on thread: A Team Thread 5
    Crunching on thread: A Team Thread 4
    Done crunching on thread: A Team Thread 4
    Crunching on thread: A Team Thread 3
    Done crunching on thread: A Team Thread 3
    Crunching on thread: A Team Thread 2
    Done crunching on thread: A Team Thread 2
    Crunching on thread: A Team Thread 1
    Done crunching on thread: A Team Thread 1Notice while Team A Thread 1 is crunching, most of the B Team threads start and finish crunching. Nothing prevents a call to an unsynchronized block of code, even if that code is called from a synchronized block.
    Jim S.

  • Intrinsic locks - static synchronized method

    I am trying to understand the "static synchronized threads" - by theory when such a thread is invoked, it has to obtain a intrinsic lock on all the static variables. I wrote a sample program, but it is not giving me the desired results.
    I have 3 threads, t1, t2, t3. t1 calls a static synchronized method crazy(), where i am using static int i. t2 and t3 calls a void function f2() and f3() which just prints i. Now i put a sleep in synchronized method crazy. I am expecting t1 to start and print i and go to sleep for 10 secs, release i and then t2 and t3 starts since crazy() holds an intrinsic lock on i. But the program calls t2 and t3 even if crazy puts the thread to sleep. What happend to the intrinsic lock on i ??
    class RunnableThread implements Runnable{
    static String i;
    void f2() {
    RunnableThread.i = "Two";
    System.out.println(RunnableThread.i);
    void f3() {
    this.i = "three";
    System.out.println(this.i);
    static synchronized void crazy() {
    try {
    i = "One";
    System.out.println(i);
    Thread.sleep(10000);
    System.out.println("Sleep done");
    catch (Exception e ) {
    e.printStackTrace();
    public void run() {
    System.out.println("Thread Name: " + Thread.currentThread().getName());
    if (Thread.currentThread().getName().equals("two"))
    f2();
    } else if (Thread.currentThread().getName().equals("three"))
    f3();
    else if (Thread.currentThread().getName().equals("one"))
    RunnableThread.crazy();
    public static void main(String args[]) {
    System.out.println("SOP from main");
    RunnableThread rt1 = new RunnableThread();
    RunnableThread rt2 = new RunnableThread();
    RunnableThread rt3 = new RunnableThread();
    Thread t1 = new Thread(rt1, "one");
    t1.start();
    Thread t2 = new Thread(rt2, "two");
    t2.start();
    Thread t3 = new Thread(rt3, "three");
    t3.start();

    lavanya.km wrote:
    I am trying to understand the "static synchronized threads"Never heard of it. You might want to clarify your terminology.
    - by theory when such a thread is invoked, it has to obtain a intrinsic lock on all the static variables. Nope. Doesn't happen.
    I wrote a sample program,Ah, I see. You're creating synchronized static methods. Those do not even come close to "obtaining an intrinsic lock on all the static variables," even if there were such a thing as an "intrinsic lock," which there isn't. A synchronized method is just shorthand for enclosing the entire body in a sync block. In the case of a non-static method, it syncs on the "this" object. In the case of a static method, it syncs on the Class object for the class where the method is declared.
    In no case does anything sync on "all the variables," static or not.

  • Calling static synchronized method in the constructor

    Is it ok to do so ?
    (calling a static synchronized method from the constructor of the same class)
    Please advise vis-a-vis pros and cons.
    regards,
    s.giri

    I would take a different take here. Sure you can do it but there are some ramifications from a best practices perspective. f you think of a class as a proper object, then making a method static or not is simple. the static variables and methods belong to the class while the non-static variables and methods belong to the instance.
    a method should be bound to the class (made static) if the method operates on the class's static variables (modifies the class's state). an instance object should not directly modify the state of the class.
    a method should be bound to the instance (made non-static) if it operates on the instance's (non-static) variables.
    you should not modify the state of the class object (the static variables) within the instance (non-static) method - rather, relegate that to the class's methods.
    although it is permitted, i do not access the static methods through an instance object. i only access static methods through the class object for clarity.
    and since the instance variables are not part of the class object itself, the language cannot and does not allow access to non-static variables and methods through the class object's methods.

  • Use of 'static' keyword in synchronized methods. Does it ease concurrency?

    Friends,
    I have a query regarding the use of 'synchronized' keyword in a programme. This is mainly to check if there's any difference in the use of 'static' keyword for synchronized methods. By default we cannot call two synchronized methods from a programme at the same time. For example, in 'Program1', I am calling two methods, 'display()' and 'update()' both of them are synchronized and the flow is first, 'display()' is called and only when display method exits, it calls the 'update()' method.
    But, things seem different, when I added 'static' keyword for 'update()' method as can be seen from 'Program2'. Here, instead of waiting for 'display()' method to finish, 'update()' method is called during the execution of 'display()' method. You can check the output to see the difference.
    Does it mean, 'static' keyword has anything to do with synchronizaton?
    Appreciate your valuable comments.
    1. Program1
    public class SynchTest {
         public synchronized void display() {
              try {
                   System.out.println("start display:");
                   Thread.sleep(7000);
                   System.out.println("end display:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public synchronized void update() {
              try {
                   System.out.println("start update:");
                   Thread.sleep(2000);
                   System.out.println("end update:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              System.out.println("Synchronized methods test:");
              final SynchTest synchtest = new SynchTest();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.display();
              }).start();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.update();
              }).start();
    Output:
    Synchronized methods test:
    start display:
    end display:
    start update:
    end update:
    2. Program2
    package camel.java.thread;
    public class SynchTest {
         public synchronized void display() {
              try {
                   System.out.println("start display:");
                   Thread.sleep(7000);
                   System.out.println("end display:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static synchronized void update() {
              try {
                   System.out.println("start update:");
                   Thread.sleep(2000);
                   System.out.println("end update:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              System.out.println("Synchronized methods test:");
              final SynchTest synchtest = new SynchTest();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.display();
              }).start();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.update();
              }).start();
    Output:
    Synchronized methods test:
    start display:
    start update:end update:
    end display:

    the synchronized method obtain the lock from the current instance while static synchronized method obtain the lock from the class
    Below is some code for u to have better understanding
    package facado.collab;
    public class TestSync {
         public synchronized void add() {
              System.out.println("TestSync.add()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.add() - end");          
         public synchronized void update() {
              System.out.println("TestSync.update()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.update() - end");          
         public static synchronized void staticAdd() {
              System.out.println("TestSync.staticAdd()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.staticAdd() - end");
         public static synchronized void staticUpdate() {
              System.out.println("TestSync.staticUpdate()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.staticUpdate() - end");
         public static void main(String[] args) {
              final TestSync sync1 = new TestSync();
              final TestSync sync2 = new TestSync();
              new Thread(new Runnable(){
                   public void run() {
                        sync1.add();
              }).start();
              new Thread(new Runnable(){
                   public void run() {
                        sync2.update();
              }).start();
              try {
                   Thread.sleep(3000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              new Thread(new Runnable(){
                   public void run() {
                        sync1.staticAdd();
              }).start();
              new Thread(new Runnable(){
                   public void run() {
                        sync2.staticUpdate();
              }).start();
    }

  • Need of more than one synchronized methods

    Inside my run method I'm calling a synchronized method which in turn calls other synchronized methods of the same and another class.
    Now if the top level method is synchronized, does the need to make other methods synchronized still remain ?
    Won't the other threads wait till the thread using the top level synchronized method returns.
    Vik

    Well, if you can be sure that the second method is not going to be called some other way except within that first synchronized method, then no it's not needed.

  • Static synchronized methods VS non-static synchronized methods ??

    what is the difference between static synchronized methods and non-static synchronized methods as far as the behavior of the threads is concerned? if a thread is in static synchronized method can another thread access simple (ie. non static) synchronized methods?

    javanewbie80 wrote:
    Great. Thanks. This whole explanation made a lot of sense to me.Cool, glad I was able to help!
    Probably I was just trying to complicate things unnecessarily.It's a classic case of complexity inversion. It seems simpler to say something like "synchronization locks the class" or "...locks the method" than to give my explanation and then extrapolate the implications. Just like the seemingly simpler, but incorrect, "Java passes objects by reference," vs. the correct "Java passes references by value," or Java's seemingly complex I/O vs. other languages' int x = readInt(); or whatever.
    In the seemingly complex case, the primitive construct is simpler, but the higher level construct requires more assembly or derivation of the primitive constructs, making that case seem more complicated.
    Okay, I just re-read that, and it seems like I'm making no sense, but I'll leave it, just in case somebody can get some meaning out of it. :-)

  • Terminating event in synchronous method.

    Hi,
    I am not using any BOR and its event in start event tab, but i want to use terminating event within a task, so can i do this?
    Within this task i am using a BOR and its method, this is Synchronous method.
    Now i want to use one terminating event also, so that this task completes either by successfully completing the method or by using terminating event.
    Can i trigger this event from non-sap system?
    Can i set container element from non-sap system? If yes how?
    Thanks in advance,
    Amar

    I am not using any BOR and its event in start event tab, but i want to use terminating event within a task, so can i do this?
    Ans. Yes...
    Now i want to use one terminating event also, so that this task completes either by successfully completing the method or by using terminating event.
    Ans. This is what a Job of Asynchronous task .. so create it as asynchronous...
    Can i trigger this event from non-sap system?
    Yes ... Use SAP_WAPI_CREATE_EVENT...
    Can i set container element from non-sap system? If yes how?
    Yes .... SAP_WAPI_WRITE_CONTAINER
    Regards
    Gautam

Maybe you are looking for