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.

Similar Messages

  • Why not to use static methods - with example

    Hi Everyone,
    I'd like to continue the below thread about "why not to use static methods"
    Why not to use static methods
    with a concrete example.
    In my small application I need to be able to send keystrokes. (java.awt.Robot class is used for this)
    I created the following class for these "operations" with static methods:
    public class KeyboardInput {
         private static Robot r;
         static {
              try {
                   r = new Robot();
              } catch (AWTException e) {
                   throw new RuntimeException(e + "Robot couldn't be initialized.");
         public static void wait(int millis){
              r.delay(millis);
         public static void copy() {
              r.keyPress(KeyEvent.VK_CONTROL);
              r.keyPress(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_CONTROL);
         public static void altTab() {
              r.keyPress(KeyEvent.VK_ALT);
              r.keyPress(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_ALT);
                   // more methods like  paste(), tab(), shiftTab(), rightArrow()
    }Do you thinks it is a good solution? How could it be improved? I've seen something about Singleton vs. static methods somewhere. Would it be better to use Singleton?
    Thanks for any comments in advance,
    lemonboston

    maheshguruswamy wrote:
    lemonboston wrote:
    maheshguruswamy wrote:
    I think a singleton might be a better approach for you. Just kill the public constructor and provide a getInstance method to provide lazy initialization.Thanks maheshguruswamy for advising on the steps to create a singleton from this class.
    Could you maybe advise also about why do you say that it would be better to use singleton? What's behind it? Thanks!In short, it seems to me that a single instance of your class will be able to coordinate actions across your entire application. So a singleton should be enough.But that doesn't answer why he should prefer a singleton instead over a bunch of static methods. Functionally the two are almost identical. In both cases there's only one "thing" on which to call methods--either a single instance of the class, or the class itself.
    To answer the question, the main reason to use a Singleton over a classful of static methods is the same reason the drives a lot of non-static vs. static decisions: Polymorphism.
    If you use a Singleton (and and interface), you can do something like this:
    KeyboardInput kbi = get_some_instance_of_some_class_that_implements_KeyboardInput_somehow_maybe_from_a_factory();And then whatever is calling KBI's public methods only has to know that it has an implementor of that interface, without caring which concrete class it is, and you can substitute whatever implementation is appropriate in a given context. If you don't need to do that, then the static method approach is probably sufficient.
    There are other reasons that may suggest a Singleton--serialization, persistence, use as a JavaBean pop to mind--but they're less common and less compelling in my experience.
    And finally, if this thing maintains any state between method calls, although you can handle that with static member variables, it's more in keeping with the OO paradigm to make them non-static fields of an instance of that class.

  • Problem referencing to methods with generic type parameters

    Assuming I have an interface like to following:
    public interface Test <T> {
    void test ( T arg0 );
    void test ( T arg0, Object arg1 );
    I would like to reference to both "test"-methods using "{@link #test(T)}" and "{@link #test(T,Object)}".But this generates an error telling me "test(T)" and "test(T,Object)" cannot be found.
    Changing T to Object in the documentation works and has as interesing effect. The generated link text is "test(Object)" but the generated link is "test(T)".
    Am I somehow wrong? Or is this a known issue? And is there a workaround other than using "Object" instead of "T"?

    Hi,
    I bumped into the same problem when documenting a generic.
    After quite a while of search your posting led me to the solution.
    My code goes something like this:
    public class SomeIterator<E> implements Iterator<E> {
      public SomeIterator(E[] structToIterate) {
    }When I tried to use @see or @link with the constructor Javadoc never found it.
    After I changed the documentation code to
    @see #SomeIterator(Object[])it worked.
    Since both taglets offer the use of a label, one can easily use these to produce comments that look correct:
    @see #SomeIterator(Object[]) SomeIterator(E[])CU
    Froestel

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

  • Memory management with static methods

    I made a class with no attributes and only static methods with the purpose of maintaining as little as possible about it in memory. What information is kept in memory by the JVM about such a class ?
    Thanx in advance :)

    Static methods don't consume less memory than regular instance
    methods. Well, not exactly: a regular method requires a reference
    to an instance as a hidden additional parameter. Thus, specifying
    static for methods that don't access the object may actually save
    a few bytes. However, the code is not duplicated for each instance.
    Additionally, the JVM must keep any initialization values and the
    names of the class and the methods, as needed by reflection.
    Given suitable debugging options, local variables names and line
    number may be kept in memory as well. Finally, all hosekeeping
    info (gc, references and the like) must be kept in memory.

  • Generic static methods in a parameterized class

    Is there anything wrong with using generic static methods inside of a parameterized class? If not, is there anything special about defining them or calling them? I have a parameterized class for which I'd like to provide a factory method, but I'm running into a problem demonstrated below:
    class MyClass<T> {
         private T thing;
         public
         MyClass(T thing) {
              this.thing = thing;
         public static <U> MyClass<U>
         factoryMakeMyClass(U thing)     {
              return new MyClass<U>(thing);
    class External {
         public static <U> MyClass<U>
         factoryMakeMyClass(U thing)     {
              return new MyClass<U>(thing);
    class Test {
         public static void
         test()
              // No problem with this line:
              MyClass<String> foo = External.factoryMakeMyClass("hi");
              // This line gives me an error:
              // Type mismatch: cannot convert from MyClass<Object> to MyClass<String>
              MyClass<String> bar = MyClass.factoryMakeMyClass("hi");
    }Does this code look ok to you? Is it just a problem with my ide (Eclipse 3.1M2)? Any ideas to make it work better?

    I've been working on essentially the same problem, also with eclipse 3.1M2. A small variation on using the external class is to use a parameterized static inner class. I'm new enough to generics to not make definitive statements but it seems to me that the compiler is not making the correct type inference.
    I think the correct (or at least a more explicit) way of invoking your method would be:
    MyClass<String> bar = MyClass.<String>factoryMakeMyClass("hi");
    See http://www.langer.camelot.de/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ401
    See http://www.langer.camelot.de/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ402
    Unfortunately, this does not solve the problem in my code. The compiler reports the following error: The method myMethod of raw type MyClass is no more generic; it cannot be parameterized with arguments <T>.
    Note that in my code MyClass is most definitely parameterized so the error message is puzzling.
    I would like to hear from more people on whether the sample code should definitely work so I would appreciate further comments on whether this an eclipse problem or my (our) misunderstanding of generics.     

  • How do you invoke a method with native int array argument?

    Hi,
    Will someone help me to show me a few codes samples on how to invoke a method which has only one argument, an int [] array.
    For exampe:
    public void Method1(int [] intArray) {...};
    Here is some simple code fragment I used:
    Class<?> aClass = Class.forName("Test2");
    Class[] argTypes = new Class[] {int[].class};
    Method method = aClass.getDeclaredMethod("Method_1", argTypes);
    int [] intArray = new int[] {111, 222, 333};
    Object [] args = new Object[1];
    args[0] = Array.newInstance(int.class, intArray);
    method.invoke(aClass, args);I can compile without any error, but when runs, it died in the "invoke" statement with:
    Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at Test1.invoke_Method_1(Test1.java:262)
         at Test1.start(Test1.java:33)
         at Test1.main(Test1.java:12)
    Any help is greatly appreciated!
    Jeff

    Sorry, my bad. I was able to invoke static methods and instance methods with all data types except native int, short, double and float, not sure the proper ways to declare them.
    After many frustrating hours, I posted the message for help, but at that time, my mind was so numb that I created a faulted example because I cut and pasted the static method invocation example to test the instance method passing int array argument.
    As your post suggested, "args[0] = intArray;", that works. Thanks!
    You know, I did tried passing the argument like that first, but because I was not declaring the type properly, I ended up messing up the actual passing as well as the instantiation step.
    I will honestly slap my hand three times.
    jml

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • Can we override Static methods?

    Hi all, I m in little bit confusion abt static methods overriding.
    Could you help me on this issue.,
    Can we override Static methods?

    You can provide static methods with same name in both super class and subclass. But it is not overriding in this scenario. Both will act as independent methods.
    Example:
    have a super class:
    public class Test1 {
    public static void mthdA()
    System.out.println("in super");
    have a sub class:
    public class Test2 extends Test1{
    public static void mthdA()
    System.out.println("inside sub");
    public static void main(String[] args){
    Test1 objTest = new Test2();
    objTest.mthdA();
    Try to run the sub class Test2. The output would be "in super".
    Remove static modifier in mthdA() in both the classes and then run. The output would be "in sub". Meaning, methdA is overriden in sub class.

  • Over riding static methods

    hi i wrote two static methods with same signatures in two different classes. i know that static methods never override.but observe this code..
    class staticoverload1
    static void display()
                   System.out.println("i am from first display");
    class staticoverload2 extends staticoverload1
         static int a=10;
         static void display()
              staticoverload1.display();
              System.out.println("the value of x is:"+a);
    class staticoverload
         public static void main(String args[])
              staticoverload2 s1=new staticoverload2();
              s1.display();
    i got output as follows:
    i am from first display
    x value is :10
    in the above problem over riding is happened or not

    Please post your code in code tags.
    s1.display();
    Don't call static methods on objects. Tis ugly. But it will use the type of the reference.
    class Test {
         public static void display() {
              System.out.println("Test");
         public static void main(String[] argv) {
              Test t = new Test2();
              t.display(); // Prints "Test". Even if you set it to null.
    class Test2 extends Test {
         public static void display() {
              System.out.println("Test2");
    }Finally this should have been posted in New To Java.

  • Are Static methods Thread safe?

    Hello All
    I have a static method that takes a integer and returns a mathematically processed result.
    Since this method is frequently required, I have placed it in a common class and declared it as static.
    I want to know whether this method is thread safe?

    There's nothing special about static methods, with regard to thread safety. If they access shared objects, then such access will usually need to be controlled by synchronisation; this might be on the object being accessed, some higher-level object or a special object allocated purely as a lock. The only way that you might think of them as special is that there's no instance of the Class on which you can synchronise.
    You can declare a static method as synchronised. If you do, it will be synchronised on the single Class object of the class in which it is declared. This means that only one thread can be executing any part of the method at any one time. However, I understand that the Java Runtime itself sometimes synchronises on this Class object for its own reasons, therefore you might sometimes find a synchronised static method blocks when no other thread is executing it. Usually better, therefore, to explicitly synchronise on some object or other, than to use synchronised static methods.

  • Calling a java static method from javascript

    I am running into issue while calling a java static method with a parameter from javascript. I am getting the following error. Any help is greatly appreciated.
    Thx
    An error occurred at line: 103 in the jsp file: /jnlpLaunch.jsp
    pfProjectId cannot be resolved to a variable
    =================================================
    // Java static method with one parameter
    <%!
    public static void CreateJnlpFile(String pfProjectId)
    %>
    //Script that calls java static method
    <script language="javascript" type="text/javascript">
    var pfProjectId = "proj1057";
    // Here I am calling java method
    <%CreateJnlpFile(pfProjectId);%>
    </script>
    ===================================================
    Edited by: 878645 on Mar 6, 2012 11:30 PM

    Thanks, Got what you are telling. Right now I have one jsp file which is setting the parameter 'pfProjectId' and in another .jsp I am retrieving it. But I am getting null valuue
    for the variable. I am wondering why I am getting null value in the second jsp page?.
    Thx
    ====================================================================
    <script language="javascript" type="text/javascript">
    // Setting parameter pfProjectId
    var pfProjectId = "proj1057";
    request.setParameter("pfProjectId", "pfProjectId");
    </script>
    // Using Button post to call a .jsp that creates jnlp file
    <form method=post action="CreateJnlpFile.jsp">
    <input type="submit" value="Create JNLP File">
    </form>
    //Contents of second .jsp file CreateJNLPFile.jsp
    String pfProjectId = request.getParameter("pfProjectId ");
    System.out.println( "In CreateJnlpFile.jsp pfProjectId " + pfProjectId );
    =======================================================

  • Actual Benefits of final methods and final parameters

    I know that a lot of this depends on the JVM and the actual code, but I was wondering what the actual real world advantage was of using final methods and final parameters.
    I use a business and data layer for my program to interact with the database. So all of the methods in these classes are public and static. I was just wondering if it would be benefical to make all of these methods final and all of the parameters final also. I won't ever be making subclasses of these classes, so is this worth doing?
    Thanks,
    Dave Johansen

    On the point of final, this should always be a design decision. That is, does it make sense to allow your class to be overridden? Making classes and/or methods final is a big barrier to future enhancements and extendability - so only make soemthing final if you haver a specific reason for doing so.
    Any performance issues should not take a high precedence in this decision - and in any case the difference in making something final will be non-existant for all practical purposes.
    How about volatile?
    I get the meaning of synchronized but
    volatile?Volatile is a keyword that tells the JVM it can't optimize / inline serctions of code that use certain variables. You may not realise it, but the JVM takes your bytecode and chops them up and re-arranges them at runtime, to boost performance. This can sometimes have dangerous consequences in a mutlithreaded environment, so by adding the volatile keyword you are saying to the JVM (or specifically HotSpot) not to perform any "code magic".
    Here's a simple example:
    public class TestClass {
        private boolean check = false;
        public void setTrue(){
            check = true;
        public void check(){
            check = false;
            if(check){
                System.out.println("Will this ever print?");
    }Obviously the string will never print in a single threaded environment. However, in a multithreaded environment, is is possible that a thread could call setTrue() between another thread setting the value to false and performing the if() check. The point is that due to runtime optimization, Hotspot may realise that check is always false, so completely remove the code section with the if block. so regardless of the value of the boolean, the code may never be entered.
    One solution is to declare the boolean check as volatile. This tells the JVM that such optimizations are not allowed and then it is entirely possible for the string to be printed.
    One curiousity, off-topic:
    is there a way for jvms instantiations to see each
    other?Have you looked into RMI?

  • What's wrong with static methods?

    Answers on an postcard please.

    I think the point here is that sometimes people come from a procedural background (or maybe no background) and they start with main, and one static method leads to another. They reach a tipping point where they are reluctant to define non-static methods to a class because it's all static elsewhere. And static method can't access instance data, so their data becomes largely static as well. When the dust settles, they are programming procedually in Java. So too many static methods is a sign that you may be programming procedurally instead of doing OOP, but using static appropriately is still cool.
    And let's not get pedantic. What goes wrong if I make my String class's getLength method static?
    public final class MyString {
        private int length;
        public static int getLength(String s) {
            return s.length;
    }It's a misuse of static, but it doesn't break my design.

  • Shoukd the 'final' keyword should be used on all input parameters?

    In my very limited experience as a java programmer have never seen this done any where. Except in the java.lang.Math class which has a final variable, of type double, called PI. As pi is not a value that should change during the execution of a program, though this is not passed in as a parameter.
    However, on a new project, a co-worker is proposing the use of the 'final' keyword on all input parameters as a standard. He has about 5 years experience of maintaining java systems and is putting this suggestion forward as in the past people have overwritten values passed in as parameters causing confusion. Personally I don't see why this is such a major issue if one reads the code of the called programs.
    I would be grateful if anyone has seen this done before, or has any views on the advantages or disadvantages of this.
    Thanks in advance,
    LS

    Lord_Sidcup wrote:
    In my very limited experience as a java programmer have never seen this done any where. Except in the java.lang.Math class which has a final variable, of type double, called PI. As pi is not a value that should change during the execution of a program, though this is not passed in as a parameter.
    I'm sorry, but this point is irrelevant. There are lots of final fields (but not that many final parameters) in Java, BTW. Every field you declare in an interface is automatically final, for example.
    However, on a new project, a co-worker is proposing the use of the 'final' keyword on all input parameters as a standard. He has about 5 years experience of maintaining java systems and is putting this suggestion forward as in the past people have overwritten values passed in as parameters causing confusion. Personally I don't see why this is such a major issue if one reads the code of the called programs.
    IMHO, it's definately not a major issue. It is simply being restrictive, to be restrictive. The guy may have "five years experience", but he sounds lazy, to me. Besides, the first thing I would do in that case (if final were the default), would be something like this:
    public void myMethod (final String a, final int b) {
      String myA = a;
      String myB = b;
    }And now, what has he won by making it final? It simply added some up front work for some people, with no real added value. Also, if I had to retroactively change my code, I would change it as follows:
    //Original Code
    public void myMethod (String myA, int myB) {
      String myA = a;
      String myB = b;
    // New code
    public void myMethod (final String a, final int b) {
      String myA = a;
      String myB = b;
    }That way, you wouldn't even have to worry about changing anything else about your method, as the variables actually used in the rest of the body will remain the same.
    I would be grateful if anyone has seen this done before, or has any views on the advantages or disadvantages of this.The only thing declaring the parameter final does, is it prevents you from assigning a new value to the variable. The instance that parameter references (as long as it is not immutable to begin with) can still be manipulated. I.E. except in some very narrow, and specific, cases, no value added, simply a restriction that exists to be restrictive.
    >
    Thanks in advance,
    LSEdit: And man, am I slow and long-winded.

Maybe you are looking for