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.

Similar Messages

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

  • Instance methods faster than sync. static methods in threaded env?

    consider the following please:
    (-) i have "lots" of instances of a single Runnable class running concurrently..
    (-) each instance uses a common method: "exponential smoothing" and they do a lot of smoothing.
    so:
    (option #1): include a "smooth()" instance method in the Runnable class.
    (option #2): include a "smooth()" synchronized static method in the Runnable class.
    (option #3): create a MathUtility class, and have "smooth()" as an instance method in this class.
    (option #4): make "smooth()" a synchronized static method in the MathUtility class.
    from OOP point of view, i think i should externalize "smooth()" to a MathUtility class, and then make
    is "synchronized static".
    but then from a performance point of view....
    would not it be optimal to make "smooth()" an instance method in MathUtility and then have each
    instance of the Runnable create its own MathUtility instance so that each thread has its own copy
    of the "smooth()" method??
    well, i can't image there would be a measurable difference so maybe i should not post.
    but, if there is a flaw in my thinking, please let me know.
    thanks.

    kogose wrote:
    from OOP point of view, i think i should externalize "smooth()" to a MathUtility class, and then make
    is "synchronized static".From an OOP point of view you should probably have a class that represents the data that provides a (non-static) smooth() method that either modifies the data or returns a new smoothed data object (depending on whether you want your data objects to be immutable or not).
    but then from a performance point of view....
    would not it be optimal to make "smooth()" an instance method in MathUtility and then have each
    instance of the Runnable create its own MathUtility instance so that each thread has its own copy
    of the "smooth()" method??No, methods are not "copied" for each instance. That just doesn't happen.
    well, i can't image there would be a measurable difference so maybe i should not post.If you don't know, then you should probably try it.
    but, if there is a flaw in my thinking, please let me know.The flaw in your thinking is that you can think that you can intuitively grasp the difference in performance of a change at that level.
    I have yet to meet anyone who can reliably do that.
    Performance optimization is not an intuitive task at that level and you should never do performance optimizations without proving that they are improvements for your particular use case.
    First part: Is the smooth() method really thread-unsafe? Does it use some shared state? My guess would be that it uses only local state and therefore doesn't need any synchronization at all. That would also be the fastest alternative, most likely.

  • Question about synchronized static function.

    Hi, everyone!
    The synchronized statement often deals with an object (called monitor).
    But a static function can be invoked without an object.
    So if a static function is declared as static, what is the function of
    static and synchronized here? Which lock it is using?
    Can you give me a simple expplanation?
    regards,
    George

    Hence try and avoid synchronizing static methods.
    Try and use non static method if you are doing
    multithreaded programming. That way you can have lockWell, I avoid static methods, not just when doing multithreading, but not for the reason you mention.
    objects which allow non interfering methods to be
    accessed in parallelThats easy to do with static methods anyway:
    class Foo
      static Object lock1 = new Object();
      static Object lock2 = new Object();
      static void method1()
         synchronized( lock1 )
      static void method2()
         synchronized( lock2 )
    }Maybe I just missunderstod you...

  • Interesting Qtion: Synchronize a static method

    I know that a non-static method and a block can be synchronized.
    Can anyone tell me as to what it means to synchronize a static method of a class and how/when is it used. I just tried compiling the code and it gives no compiler/syntactical errors.
    it would be helpful if u could take up a simple class example.
    Thanks,
    Novice

    Hi,
    A good example for using synchronized static methods is the singleton pattern. E.g.
    public class Singleton
      private Singleton() {}
      private static Singleton fgUniqueInstance;
      public static synchronized Singleton getInstance()
        if (fgUniqueInstance==null) {
          fgUniqueInstance = new Singleton();
        return fgUniqueInstance;
    }If you won't synchronize this class in a multi-threading environment, it could happen, that more than one instance is created.
    Andre

  • When a static method is accessed concurrently

    When a static method is accessed by many objects symultaneously(concurrently),
    What is happened in the static method.
    Are the stacks for that method maded seperately and
    each stack doesn't influence other stacks?
    thank you in advance.

    The static objects or methods concept is clear, one
    instance for all objects.No. One instance for the class.
    , and every
    one know that, static methods is slower than
    nonstatic, Since when? I've certainly never heard that before... Do you have a reference I can look at?
    and this is as i thought because static
    methods are syncronized by default.Absoloutely not!
    All synchronization locks on an object. When you synchronize an instance method, it locks on the implicit "this"; When you synchronize a static method, it locks on the class's associated Class object.
    So two synchronized static methods in the same class can not be called at the same time, but synchronized instance methods that access static variables can all access those variables at the same time and potentially cause threading problems. In this situation you can declare the static fields volatile or wrap synchronized blocks around all code that accesses them, and synchronize on the same object (perhaps the Class object associated with the current class would be appropriate, but that reallt depends on the rest of your design).

  • Static method vs synchronisation

    Hi,
    A fundamental query.
    If i am declaring a method as static, can i also declare it as sunchronized? i.e. can i have something like
    public static synchronized sss(){
    xxx
    If a method is static, there is only one instance in the memory. Correspondingly, only one client can execute it at a time. in which case it is automatically synchronized.
    Pl correct my reasoning.
    When do we have the requirement of having a static method, or probably a singleton??
    Thanks,
    Prashant Gupta

    Hi,
    A fundamental query.
    If i am declaring a method as static, can i also declare it as sunchronized? i.e. can
    i have something like
    public static synchronized sss(){
    xxx
    }?Yes, static methods can be synchronized which means that when any thread is running within a synchronized static method of class C, no other thread may enter a static synchronized method of that class. In other words, the monitor acquired by a static synchronized method is the Class itself while the monitor acquired by a non-static synchronized method is the object refered to by 'this'.
    If a method is static, there is only one instance in the memory. Correspondingly,
    only one client can execute it at a time. in which case it is automatically synchronized.There is (in most circumstances) a single copy of the definition (bytecodes representing all methods - static or not - and static fields) of of a class. However, any number of threads may be executing within any section of code unles that code is guarded by a synchronized block or within a synchronized method. In that case, no two threads can enter (well, actually be runnable within - Object.wait() has special implications) a synchronized block monitored by the same object.
    When do we have the requirement of having a static method, or
    probably a singleton??Not sure what you are asking here. You define static methods when there is behavior you want to implement that does not need to have access to instance (non-static) fields or methods and which would never need to be overridden (for purposes of polymorphism) by derived classes.
    Wen needing a singleton, you have a choice of defining a "true singleton" (i.e. a class with a private constructor, some sort of static getInstance() method, with the bulk of its methods anf fields are non-static) or defining a class whose methods are all static and whose fields are also all static. Singletons. Use the one that fits you needs the best.
    Chuck

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

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

  • Should I use a static method or an instance method?

    Just a simple function to look at a HashMap and tell how many non-null entries.
    This will be common code that will run on a multi-threaded weblogic app server and potentially serve many apps running at once.
    Does this have to be an instance method? Or is it perfectly fine to use a static method?
    public static int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    OR
    public int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    }

    TPD Opitz-Consulting com wrote:
    The question is the other way around: Is there a good reason to make the method static?
    Ususally the answer is: no.The question is: does this method need state? Yes -> method of a class with that state. No -> static.
    The good thing of having this method statig is that it meight decrese memory foot pring but unless you're facing memory related problem you should not think about that.I doubt there is any difference between the memory foot print of a static or not method.
    I'm not shure if this method beeing static maks problems in multithreaded environments like the one you're aiming at. But I do know that an immutable object is always thread save.Does the method use shared state (data)? No -> no multi threaded problems.
    Can the parameters be modified by different threads? Yes, if multiple threads modified the parameter map, but nothing you can do about it here (no way to force the calling thread to lock on whatever you lock on).
    So my answer to your question is: yes, it should be non static.The method should be static since it uses no state.
    It is thread-safe when only the calling thread can modify the passed map (using a synchronized or ConcurrentHashMap is not enough, since you don't call a single atomic method on the map).
    // Better use Map instead of HashMap
    // We don't care about the generic type, but that does not mean we should use a raw type
    public static int countNonNullEntries(Map<?, ?> map) {
      // whether to accept null map or not, no need for explicit exception
      // since next statement throw NPE anyway
      Collection<?> values = map.values();
      // note your method is called countNonNull, not countNull!
      // (original code it would need to by if(null != mapValue) notNullsCounter++;
      return values.size() - java.util.Collections.frequency(values, null);
    }

  • Threading with static methods

    If I have a multithreading capabilities in my program, then I invoke a static method that writes timestamp to a file. What will happen? will all threads use this same static method? or will the program crash?

    static or otherwise isn't the issue. The issue is that it's not a good idea to have two threads trying to write to the same file at the same time.
    To prevent this you need to have each thread reserve the file until it's done it's thing. If you put the synchronized keyword on the method declaration you lock any all synchronized statis methods in the class, which is probably not idea. Probably better to use some comon object as the montor e.g.
    static File timeStamp = new File("timestamp.txt");
    public static void setTimeStamp() throws IOException {
         synchronized(timeStamp) {
              Writer out = new FileWriter(timeStamp);
              out.close();
         }

  • Singleton bottleneck with static methods?

    A discussion came up at work today. If a class is created as a Singleton and only provides static methods and only final static data members (just for storing read only info like a connection string), will this create a bottleneck? Someone was suggesting that sharing the Singleton would cause each thread accessing the code to have to obtain the monitor on the class before being able to execute the method. Is this the case? None of the methods are synchronized, but they all perform atomic functionality. Anyone have any input on this?

    Currenlty, it is implemented as a Singleton, part of
    the discussion was moving everything into static
    methods. Aside from that, the question is still
    whether having a single location to run methods from
    will become a bottleneckWho came up with the idea that this would create some sort of bottleneck? Never pay attention to them again.
    Static methods are (slightly) faster than ordinary instance methods because there is no virtual method lookup. The only way there would be some sort of performance implication is if the methods are synchronized. In that case performance will be essentially the same as synchronized instance methods of a singleton.

  • 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 methods in multi-threaded environment

    Hi,
    I am wondering what happens when several threads try to access the same static method ?
    The static method is not synchronized.
    Will this create any performance issues ?
    The actual scenario is of a J2EE server, where several Session Bean instances try to access a static method in a utility class. Will some session beans have to wait till others are being serviced ?
    thnx n regards
    s giri

    thanx for replying.
    yes. the operations are thread-safe. we do not change the state of any object.
    but we make an rmi call to another application thru this static method.
    is it ok?
    Currently, my session bean has too many private methods - each calling the other application. Due to some quality metrics (a class must be restricted to 700 lines) we have to consider moving these private methods into some Helper class in the form of "public static methods". We have made many utility methods as static, but have some reservations abt doing a similar thing for these methods that call other application.
    regards
    Shivraman

Maybe you are looking for

  • Repeated retrieval and parsing of XML file causes IE to display an error message

    I have a flash application that makes a HTTP call every 120 seconds to retrieve a xml file. This file is being generated with fresh data every few minutes or so and pushed to the apache web root with a unix mv command. I'm using the standard Flash XM

  • Laptop won't turn on with AC cord attached or on battery power

    My laptop recentlystopped working and now will not turn on.  Each time that I try to power on the blue lights flash for approx. 5 sec and then go off and that is it.  Any suggestions as to what this might be?  Thank you in advance

  • Video out put not a valid format

    Hi I am having a problem with iMovie when i go to share my finnished products. It works fine when i export to DVD, but when i select to share as a full quality movie, iMovie creates the video file but when i try to run it i get an error saying Error

  • Preview size & quality settings

    Although I have been using LR for many months I am still confused as to what to set my import settings to when it comes to previews. Standard or 1:1? What quality settings? Can anyone enlighten me on best practices?

  • Data for Report Painter report

    Hi Gurus, I have a report painter report S_ALR_87013019 . This uses the Library 602 (gr23), report - 60BU-001 (GRR3). Need to create a regular report based on this, Can you Please tell from which tables the values are getting retrieved by this report