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

Similar Messages

  • Static Methods with all Final Parameters

    Gurus,
    I know the synchronization and static method question has been hashed out ad infinitum here. However, I was thinking of a slight twist. (Did a search but could not find something related to this. If this has already been posted, my apologies).
    Suppose you have a static method in which all of the parameters in the method signature are declared final. Let's assume also that you are not performing an operation with a high latency (say, database or network operations).
    Would it be "safe" to leave the static method unsynchronized in a multi-threaded environment? Would the final keyword(s) ensure that, throughout method execution, there is no longer a race condition?
    Would there be a difference between a primitive:
    static final public void doSomething(final int param) {}
    And an object that has mutator methods:
    static final public void doSomething(final List param) {}
    Basically, not having a formal CS background, I'm not sure how static methods are actually invoked on a low-level. It probably varies across JVM's, and maybe this question doesn't make much sense. However, I thought I would throw this out to see if anyone had implemented something similar.
    I might be giving "final" too much credit., but what would actually happen in a multi-threaded environment?
    Thanks much!
    - Saish
    "My karma ran over your dogma." - Anon

    I know the synchronization and static method question
    has been hashed out ad infinitum here. What question's that then?
    Suppose you have a static method in which all of the
    parameters in the method signature are declared final.
    Let's assume also that you are not performing an
    operation with a high latency (say, database or
    network operations).
    Would it be "safe" to leave the static method
    unsynchronized in a multi-threaded environment?Whether or not the parameters are final makes no difference - method parameters are local to the method and so are only visible to the current thread anyway. So making them final will have no effect on anything goning on in any other thread.
    Whether or not you are performing operations has no effect on whether or not you can call a method thread-safe. It might mean there is less contention and it might make race conditions less likely, but it won't eliminate them.
    So the answer is: If your would be thread safe with non-final parameters, then it will still be thread-safe when the parameters are all final. If it is not thread-safe with non-final parameters, then it will still not be thread safe with final parameters.
    Would the final keyword(s) ensure that, throughout
    t method execution, there is no longer a race
    condition?No. Absoloutely not.

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

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

  • Does static methods need to be synchrnized ?

    Hi All,
    I have some class (static) methods in my program running on Server-A, which call a service running on Server-B over HTTP. My program is accessed by different client threads which pass values for my class method's parameters, and my class method will return the value that it got from the service returned by Server-B.
    In such scenarion, which of the following options is better, and if you have any other option that suits well to this situation, please suggest:
    option 1: synchronize the static methods.
    option 2: modfiy the class methods to instance methods.
    option 3: leave it as it is, there is no problem.
    thanks,
    darbha.

    It looks you have to synchronize the static method (option 1).
    Only one client thread may use the HTTP connection at a time.

  • Static methods in Transfer Objects

    Hi all,
    I have a doubt about Transfer Object:
    Is it possible to have a static method (or field)
    inside a Transfer Object returned from
    a Session Bean to a Client ?
    Many thanks in advance,
    Moreno

    Static fields, yeah, they'd cause some interesting problems, so are not a good idea in TOs. You can do it, but YMMV (Your Mileage May Vary).
    Static method? I'd get rid of it and put it in a utility class or somewhere else. Static methods are pretty meaningless when applied to TOs. The idea is to encapsulate data and some behavior - not provide procedural functionality.

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

  • Are static methods in Java thread safe?

    Are static methods in Java thread safe?
    thanks,
    suresh

    if static method use the instance variable
    You mean member variable, where member variables are either class variables (static) or instance variables (non-static).
    then you have to make it thread safe using
    synchronization Not necessarily. Depends on requirements and usage context.
    else in case of local var. it
    is thread safe. Not necessarily. That local variable could refer to an object that's visible to multiple threads.
    Statements like "Local variables are threadsafe but member variables aren't" are an oversimplification.
    Something is threadsafe if it cannot be made to behave incorrectly simply by running it in a multithreaded context. Determining that can be very difficult.

  • Static methods. Why?

    I understand what static means, and that each class has only ONE copy of its static variables and methods.
    I an see the benefits of using static variables, but i cant seem to get my head round the benefits of using static methods.
    What is the advantage of this, and is there a common situation where they are appropriate? (not main)
    Cheers

    I don't think static exists to prevent namespace conflicts. I think that the reason for static to exist is just as I described it: When you've got some task that is appropriate to be performed by a specific class, but that doesn't make sense to be associated with a particular instance of that class.
    For example, String.valueOf. It's appropriate for the String class to have a method that returns the String representation of anything you feed to it (so it's in the String class) but it doesn't make sense for that method to be associated with a particular instance of String (so it's static). After all, you don't yet have a String to operate on--you're producing the String.
    Which raises another interesting point: I wonder what the design decision was that led to
    String.valueOf(int)
    String.valueOf(long)
    String.valueOf(Object)
    etc.
    instead of
    new String(int)
    new String(long)
    newString(Object)
    etc.
    I've used both patterns in my own work, but I don't really have any good criteria for picking one over the other.
    One thing that comes to mind for the general case is that with the static method, you can return a subclass, which you can't do with a constructor. Conversely, with a constructor, the caller knows exactly which class he'll get, whereas with a static method he doesn't. Of course, these points don't apply to String, as it's final.
    I'm new to java, but as far as I can tell, "static"
    means "global". The reason for having them in classes
    is mainly to prevent name conflicts. For instance,
    you could have an Array object, and a List object, and
    both could have sort() methods, but they may be very
    different types of methods. By forcing sort() to be a
    member of a class, instead of a global identifier, you
    have Array.sort() and List.sort(), which is much
    safer.
    It seems that the java designers went to great lengths
    to make sure there are no namespace conflicts in the
    language. Maybe they even went a bit too far in this
    sometimes.

  • Static method doubt

    Hi,
    I have a doubt using static methods:
    If 2 users call the same static method wih diferente parameters, the parameters of first user are changed?
    Thanks,
    rjc

    I already read that the only problem is if i acess
    and change static variables, in these cases i have
    to synchronize the method, is this true?Certainly, it is. If more than one thread are trying to change the same "thing" by using a method, you have to synchronize this method. Or you can synchronize this "thing", too.

  • Why is the static method in the superclass more specific?

    Why is the static method in the superclass more specific than the static method in the subclass? After all, int is a subtype of long, but Base is not a subtype of Sub.
    class Base {
        static void m(int i){ System.out.println("Base"); }
    class Sub extends Base {
        static void m(long l){ System.out.println("Sub"); }
    class Test {
        public static void main(String[] args) {
            int i = 10;
            Sub sub = new Sub();
            sub.m(i);
    }The first example compiles without error.
    Output: Base
    class Base {
        void m(int i){ System.out.println("Base"); }
    class Sub extends Base {
        void m(long l){ System.out.println("Sub"); }
    class Test {
        public static void main(String[] args) {
            int i = 10;
            Sub sub = new Sub();
            sub.m(i);
    }In the second example, both instance methods are applicable and accessible (JLS 15.12.2.1), but neither is more specific (JLS 12.2.2), so we get a compiler error as expected.
    : reference to m is ambiguous,
    both method m(int) in Base and method m(long) in Sub match
    sub.m(i);
    ^
    1 error
    Why don�t we get a compiler error for the static methods?

    Thank you for your ideas.
    ====
    OUNOS:
    I don't get Sylvia's response. This is about static methods, what are instances are needed for??Yes, the question is about static methods. I included the example with non-static methods for a comparison. According to JLS 15.12.2, both examples should cause a compiler error.
    And why you create a Sub object to call the method, and dont just call "Sub.m(..)"Yes, it would make more sense to call Sub.m(i). Let�s change it. Now, I ask the same question. Why is there no compiler error?
    ====
    DANPERKINS:
    The error in your logic stems from calling static methods on instances, as ounos pointed out. Solution: don't. You won't see any more ambiguities.A static member of a class may also be accessed via a reference to an object of that class. It is not an error. (The value of the reference can even be null.)
    Originally I was looking only at the case with non-static methods. Therefore, I used sub.m(i). Once I understood that case, I added the static modifiers. When posting my question, I wish I had also changed sub.m to Sub.m. Either way, according to JLS 15.12.2, a compiler error should occur due to ambiguous method invocation.
    ====
    SILVIAE:
    The question was not about finding an alternative approach that doesn't throw up an ambiguity. The question related to why, in the particular situations described, the ambiguity arises in only one of them.
    Yes.
    Proposing an alternative approach doesn't address the question.
    Yes.
    ====
    If anyone is really interested, here is some background to the question. Some people studying for a Sun Java certificate were investigating some subtleties of method invocations:
    http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=019182
    I remember seeing the non-static case discussed in this forum once before in a more practical context. jschell probably knows the link.

  • Overriding static method

    hi all
    can be override static method.if yes then how?plz explain.

    Static methods do hide rather than override - the superclass-and-above methods are, however, visible via explicit referencing. Example:
    public class Foo
         public static final void main(String[] args)
              Foo.foo();
              Poo.foo();
              Foo.bar();
              Poo.bar();
         public static void foo()
              System.out.println("Foo foo");
         public static void bar()
              System.out.println("Foo bar");
         public static class Poo extends Foo
              public static void foo()
                   System.out.println("Poo foo");
              public static void bar()
                   System.out.print("Poo bar, calling foo(): ");
                   foo();
    }Gives
    Foo foo
    Poo foo
    Foo bar
    Poo bar, calling foo(): Poo fooAlways more interesting to try stuff and just see what happens, don't you think? :o)
    Message was edited by:
    itchyscratchy - line wrap pasting error

  • Call static method from jsp expression

    Hi, I'm using adf/bc 10.1.3.4 I'm wanting to call a static method of a class when an af:commandLink is clicked. This action attribute value for this af:commandLink would be an el expression. As an example, let's say I want to call a new static method, named test(), I've added to ADFUtils.
    My af:commandLink looks like this:
    <af:commandLink action="#{ADFUtils.test}" />
    Obviously, this doesn't work. I can describe my actual use case if it would help. For now I'll just say that I don't want to use a managed/backing bean to house this method. How can I create a class to house this method w/o using a managed bean and adding that managed bean reference to the faces-config.xml?? Thanks, James

    thanks for the interest john. i'll explain what it is i'm trying to do. I have two web applications, appA and appB, both running in the same app server instance. The apps are related in the sense that once the user logs in thru an sso mechanism, they can 'bounce' back and forth between applications. Not sure if that info is relevant, but I wanted to include it anyhow.
    We've created a common banner/header jsp that we include in every page of appA and appB. Included in that header jsp is a logout link (af:commandLink), which will need to execute some code when clicked. Here is where the dilemma starts. We don't really want to have to write the code for the logout in a managed/backing bean because although both applications can use that same bean (we have it set up in the repository so that when a checkout/update is done on either appA or appB, each app, utilizing an svn external rule, would get both the banner jsp and the logout code that goes with it), making good use of the reusability concept, we would also have to add a reference to that backing/managed bean in the faces-config.xml of each application in order for it to be instantiated and used by each app. I was hoping to implement a solution which wouldn't require the developer to have to do any 'setup' on an application by application basis to use the header jsp and the code behind the Logout link. I've described a simple scenario, but in reality we'll have multiple applications, which means multiple places (faces-config.xml) where we'd need to add a reference to the managed bean which contains the logout code. It wouldn't be the end of the world for us if we ended up doing it this way, but I just have a feeling like there may be a better way to implement this so that each application's faces-config doesn't need to be touched. Hope my explanation is clear. thanks for any help you can offer.
    Edited by: kcjim on Feb 25, 2009 8:21 AM
    Edited by: kcjim on Feb 25, 2009 8:22 AM

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

  • Can static methods overridden

    help me to know that static methods can be overridden with example

    No u can not override static,private or final methodsIt would be interesting for the OP to know why (the reason is very different in each of the three cases).
    @OP: the same question was posted a fey days ago and I posted there a reply, if you do a search in the forum you'll find it.

Maybe you are looking for

  • SFTP Issue in OSB invocation resulted in an error: java.util.NoSuchElement

    I created a Proxy Service to do SFTP Poll to read the file from abcserver and its working fine . (OSB is on abc server). known_hosts file is present on OSB server. It has abcserverhostname,IP ssh-rsa AA................. == I created a business servic

  • Quicken

    If you need to use multiple currencies, DON'T BUY QUICKEN 2007 FOR MAC. It can only handle $. There is NO SUPPORT from Intuit, and you can't get your money back for this TOTALLY INFERIOR PRODUCT. The only reply from Intuit is "Your comments have been

  • 2nd MBP has messed up my home network--help please

    I have a linksys wireless router. I have a MBP 1.83 gz and my MBP 2.2 GZ just arrived today. I turned them both on, both will get onto my wireless network (which is WEP protected) and then after two or three minutes neither computer can go online. In

  • Home Directory Synchronisation and "DS_Store" files

    I have five clients on Tiger connected to a Tiger server. All clients are 10.4.8. Initially I turned Home Synchronising on, but since turned it off, realising I don't really need it. One of the clients, with the biggest profile, still keeps synchroni

  • Iphoto isn't reading my clicks

    I use iphoto 08 to edit and organize my pictures. What I usually do is zoom in on a single picture (not full screen, just zoomed into the max) and arrow threw the pictures and drag the ones I want into albums I've made. One day it stopped letting me