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. :-)

Similar Messages

  • Synchronized Static & Non Satatic methods

    Is synchronized static method acquire lock ? I have wriietn a code in which i synchronized a static & non static(instance) method. but statc method call is not acquiring a lock.
    If its not posible then there is a chance of corruption of static data.
    plz inform me
    my code is given below
    public class TestThread{
         private static int i=0;
         public synchronized static void m1(){
              System.out.println("1 Static M1 \t");     
              i++;     
              try{Thread.sleep(10000);}
              catch(Exception e){e.printStackTrace();}
              System.out.println("2 Static M1 \t");
         public synchronized void m2(){
              System.out.println("1 Static M2 \t");
              i++;
              try{Thread.sleep(10000);}
              catch(Exception e){e.printStackTrace();}
              System.out.println("2 Static M2 \t");
         public static void main(String[] args){
              new Thread(){
                   public void run(){     
                        TestThread.m1();               
              }.start();
         try{Thread.sleep(100);}
         catch(Exception e){e.printStackTrace();}
              new Thread(){
                   public void run(){     
                        new TestThread().m2();               
              }.start();

    Your example has two methods, both of which modify a static integer of the same class.
    Both of your methods are synchronized - but - one is static and one isn't. A synchronized static method aquires the 'lock' of the class, where as a non-static method aquires the 'lock' of the object.
    For this reason, your two method calls are locking on different objects and so they may be invoked by different threads executing at the 'same time'.
    Just to clarify, you can see this:
    class Test {
      private static int i = 0;
      public static synchronized modifyStatic() {
        ++i;
      public synchronized modify() {
        ++i;
    }As being this:
    class Test {
      private static int i = 0;
      public static modifyStatic() {
        synchronized(Test.class) {
            ++i; 
      public modify() {
        synchronized(this) {
          ++i;
    }So, as you can see from above, the two locks aquired are not the same.
    Dave

  • 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.

  • Static synchronized method

    hi,
    I am unable to understand the concept of static synchronized method.
    A non-static synchronized method gets lock on this object before entering into the method. But how this is valid for static method.
    thanks in advance

    hi,
    I am unable to understand the concept of static
    atic synchronized method.
    A non-static synchronized method gets lock on
    this object before entering into the method.
    But how this is valid for static method.
    thanks in advanceIt locks the YourClassName.class object.

  • 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

  • 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.

  • 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();
    }

  • Synchronized and static methods

    I've got a doubt: is it possible to apply syncrhonized to a static method? I know that synchronized takes a lock on the current object, but in the case of a static method there could be no object.
    So how can I synchronize a static method?
    Thanks,
    Luca

    previous X POST(s) :
    http://forum.java.sun.com/thread.jsp?forum=31&thread=411296
    http://forum.java.sun.com/thread.jsp?forum=31&thread=411285
    http://forum.java.sun.com/thread.jsp?forum=31&thread=390499
    http://forum.java.sun.com/thread.jsp?forum=31&thread=374388
    http://forum.java.sun.com/thread.jsp?forum=31&thread=325358
    BOTTOM LINE : Search the forum b4 posting.
    rgds.

  • 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.

  • Synchronized static method -is there a problem?

    Hi.
    I'm facing a problem. I have a common java class that is used by many applications. Class is in a jar file and is in server's shared library. And every applications in the server used it.
    Methods are declared static but not synchronized static. Class itself is not static. I have found that sometimes right after server is restarted and applications are using this class, method return values are mixed up or method behaviour is strange. I havent able to repeat this problem when testing with just one application.
    Is the problem static method and when using under one classloader (in shared lib) probelm occurs? So if i declare it static synchronized, does that solve my problem?

    Ok. But is it still risk to use static classes or
    static methods/fields in class that are shared with
    multiple applications ie. in servers shared library?That's a big fat YES.
    I suspect that you might benefit from investing a couple of hours in the "concurrency" tutorial
    http://java.sun.com/docs/books/tutorial/essential/concurrency/

  • Synchronized on static methods

    It's my understanding that the synchronized keyword attached to a method by default locks on this.
    public synchronized void red () {
      doStuff();
    }is equivelant to:
    public void red () {
      synchronized (this) {
        doStuff();
    }But, what about synchronized on static methods? What is the synchronization object for static methods?
    public synchronized static void blue () {
      doStuff();
    }is equivelant to what?

    oh yeah! man! but you get what I mean, it syncs on theYes, we do, but the compiler doesnt...
    Class object, I guess...Stop guessing...

  • Synchronized static method???

    Hi!
    What does it means "synchronized static" method? What object in this case has a lock monitor?
    class MyClass  {
    public synchronized static someMethod() {
    }Is it the equivalent to:
    synchronized ( MyClass.class ) {
    Anton

    The JVM creates a Class object when the class is loaded (When it is used for the first time) the
    JVM creates one instance of Class for each class that is loaded, thus a class itself has a moniter
    which a thread can gain ownership of.

  • Synchronizing methods and a static main method

    I have a class with a static main method, calling 3 different jdbc updates.
    I want to make sure this is thread safe when called for various clients.
    It's goes:
    args[0] = clientI
    update 1:update field1 where clientid = client1
    update 2:update field2 where clientid = client1
    update 3:update field3 where clientid = client1I assume I am in jeopardy of mixing up my data?
    I don't think I can synchronize a main method, nor would it do any good to synchronize the class?
    Should I break the updates into methods, then synchronize them, or synchronize parts of the code?
    you opinion would help greatly.

    You haven't provided enough information.
    Are those updates occurring sequentially? Then it's threadsafe.
    Are they running in different threads? Then to make them threadsafe you'll need proper synchronization, or a database transaction.
    Of course, looking at those particular updates, I don't see any reason why you'd need to worry about thread safety. They look to be independent of each other. Or perhaps you meant you need them to be atomic? That is, any query will see either the old values of all three fields, or the new values of all three fields. Nobody will be able to see the new values for fields 1 and 2, but the old value for field 3. If that's the case, then those three updates need to be in a database transaction.

  • Non-static method paint cannot be referenced from static context

    i cant seem to figure out this error dealing method paint:
    public class TemplateCanvas extends Canvas implements Runnable {
        //static
        public static final int STATE_IDLE      = 0;
        public static final int STATE_ACTIVE    = 1;
        public static final int STATE_DONE      = 2;
        private int     width;
        private int     height;
        private Font    font;
        private Command start;   
        private int state;
        private String message;
        public TemplateCanvas() {
            width = getWidth();
            height = getHeight();       
            font = Font.getDefaultFont();
            //// set up a command button to start network fetch
            start = new Command("Start", Command.SCREEN, 1);
            addCommand(start);
        public void paint(Graphics g) {
            g.setColor(0xffffff);
            g.fillRect(0, 0, width, height);
            g.setColor(0);
            g.setFont(font);
            if (state == STATE_ACTIVE) {
                Animation.paint(g);
            } else if (state == STATE_DONE) {
                g.drawString(message, width >> 1, height >> 1, Graphics.TOP | Graphics.HCENTER);
        public void commandAction(Command c, Displayable d) {
            if (c == start) {
                removeCommand(start);
                //// start fetching in a new thread
                Thread t = new Thread(this);
                t.start();
        public void run() {
            state = STATE_ACTIVE;
            //// start network fetch
            Network network = new Network();
            network.start();
            //// start busy animation
            Animation anim = new Animation(this);
            anim.start();
            //// wait for network to finish
            synchronized (network) {
                try {
                    wait();
                } catch (InterruptedException ie) { }
            //// end animation
            anim.end();
            //// get message from network
            message = network.getResult();
            //// repaint message
            state = STATE_DONE;
            repaint();
    }TemplateCanvas.java:38: non-static method paint(javax.microedition.lcdui.Graphics) cannot be referenced from a static context

    Animation.paint(g); paint() is not a static method. That means you have to call it on an instance of an Animation class (an object), not on the class itself. This is designed this way because the paint() method uses variables that have to be instantiated, so if you don't have an instance to use, it can't access the variables it needs. Static methods don't use instance variables, they only use what's passed in to them, so they don't need to be called on an object. Hope that was clear.

  • Static Verse Non-Static Methods

    Let say I was going to write a class that contained
    methods to do the same thing as itoa() and atoi() functions
    in C. What would be the pros and cons of making those
    methods static verses non-static?

    Many thanks to all.
    In summary, (correct me if I am wrong or misunderstood)
    1) methods only needs to be instance methods if they use/access
    instance variables, otherwise class/static methods are preferred
    because then, one does not have to create an instance of the
    object and keep track it.
    2) relative to threads, a method only needs to be synchronized
    if it uses/accesses shared data.
    3) most likely, not very efficient to write wrappers for one
    liners like: Integer.parseInt(String s); etc.

Maybe you are looking for

  • Using rman to backup a remote database

    I am after a good guide or advice on how (what) to install and (how to) run Oracle RMAN to backup a remote Oracle database. RMAN must be installed and run on a Solaris (SunOS 5.8) box remote from the Solaris box (also SunOS 5.8) running the Oracle da

  • How do I transfer photos from one device to another

    I have an iPhone 4S and an iPad 4. Both have the latest version of iOS. Both are connected to iCloud using the same account. If you go to Settings > iCloud > Photo Stream, both have "My Photo Stream" set to "On." I would like to be able to take a pho

  • Help with removing an Apple ID

    Hello all, I hope you can help At my place of work, we have a business contract with Vodafone, which means we get discounts on Iphone 4s through them to give out to employee's as work phones We have had someone who has left the company and handed in

  • IPhoto sort order problem

    After install of 4.2 IPhoto only syncs in date order on Ipad. Will not sort in alphabetic order despite trying numerous times.

  • FI -AP Extraction

    Hi, I am new to the FI Extraction.i need FI-AP,FIAR,FI-GL  Standard reoprts. I found AP haveing only one standard report is available "Vendor overview"i used 0FI_AP_1 data source, but this ds info package shows only full update.their is no delta...wh