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.

Similar Messages

  • Is Static Function faster than non-static function

    Hi,
    I am wondering the performances issues of static Vs non-static function.
    To prevent object creation, I wrote some static function in my class but I wonder if it really did faster.
    any pointers in this direction will be helpful
    Jacinle

    to mattbunch
    I still haven't pinpointed exactly the system
    bottleneck
    but I do think finding a better approach at the
    earliest time is betterActually, the generally accepted best practice is to start with good algorithms and data structures, write the code, test the code, profile the code, and then do this kind of nickel and dime optimization after specific bottlenecks have been pinpointed. You absolultely should not make a static/non-static decision based on performance considerations. In fact, the idea that non-static is slower due to object creation is rather muddy thinking. You'd either already have the object and invoke its non-static method, or you'd invoke a static method. In the static case, your design would probably be different anyway, so you can't predict whether time saved by not creating an object would be lost by executing other code paths.
    The case in which you count object creation time is if you're creating an object just to call this one method on it and get that method's result, and then not using the object anymore. In that case, the method should be static--not for performance reasons, but rather because the way you are using it suggests that the appropriate design is for it to be static.
    >
    so many decision to be made in designing software
    I wonder if there is any practise I can follow
    See "Thinking in Java" by Bruce Eckel, and "Practical Programming in Java" by Peter Haggar

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

  • Can one combine static and instance methods?

    Hi,
    Can one define a method so that is can be used as both a static or an instance method?
    Basically I'm trying to simplify my class to so that I can call a method either statically with parameters or instantiated using it's own attributes.
    In other words, I'm trying to accomplish both of these with one method:
    zcl_myclass=>do_something_static( im_key = '1234' ).
    lv_myclass_instance->do_something( ).   " key in private attributes
    Why would I want to do that?
    I would like to avoid instantiation in some cases for performance reasons and would like to keep it simple by having only one method to do basically the same thing.
    Any input or alternative suggestions welcome.
    Cheers,
    Mike

    Ok, I may be reaching here a bit, I know, but maybe this may give you some ideas.  After creating the object, pass it back to the method call.
    report zrich_0001.
    *       CLASS lcl_app DEFINITION
    class lcl_app definition.
      public section.
        data: a_attribute type string.
        class-methods: do_something importing im_str type string
                                   im_ref type ref to lcl_app optional.
    endclass.
    *       CLASS lcl_app IMPLEMENTATION
    class lcl_app implementation.
      method do_something.
        if not im_ref is initial.
           im_ref->a_attribute = im_str.
          write:/ 'Do_Something - ',  im_ref->a_attribute.
        else.
          write:/ 'Do_Something - ',  im_str.
        endif.
      endmethod.
    endclass.
    data: o_app type ref to lcl_app.
    start-of-selection.
      create object o_app.
      call method o_app->do_something(
               exporting
                   im_str = 'Instansiated'
                   im_ref = o_app ).
      call method lcl_app=>do_something(
               exporting
                   im_str = 'Static' ).
    Regards,
    Rich Heilman

  • Name space conflict between static and instance method

    Hello,
    there seems to be a very unfortunate name space conflict between static and instance method name. Consider:
    static String description() that should return a description of a class.
    String description() that should return a description of an instance.
    That seems to confuse the compiler. How come? Static and instance methods don't have anything to get confused about.
    Thanks for any insights :-)

    Umm...jeez.
    It's not a bug, it's the way it's supposed to be.
    Since a static method can be called the same way an instance method
    A instance = new A();
    A.staticMethod();
    instance.staticMethod();it's not allowed.
    Also in the class, you can call
    public void myMethod() {
          instanceMethodInClass();        // You don't need this, it's superfluous
          staticMethodInClass();          // You don't need the class name.
    }If you didn't understand, then just accept the fact that it is so. Some day you'll understand it.

  • This static method cannot hide the instance method from...

    What means the error message "This static method cannot hide the instance method from Referee"?
    Referee.java is a interface. I implemented it in the class RefereeMyName.java and made a method in that class to be static. Thats why I received that error message.
    But can't I use static methods when I have implemented a interface in that class? I want to have a Player.java class which I want to access RefereeMyName.getTarget(). I cannot use a instance instead because I wouldn't receive a valid return value then (RefereeMyName is the client class).
    What is the solution?

    Hi,
    Well i do not think that you can do that b'cos that way you are not giving the same signature for the method as that exists in the interface. I do not know how other way it can be done but if something urgent for you then you can remove that method from that interface and only define in the class.
    Regards,
    Shishank

  • Write to static field from instance method

    instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice.
    public static loadingDialog StatusWndw = null;
    StatusWndw = new loadingDialog(this);
    iwant to acces this satic field out side the class.
    how to slove this problem

    Make the LoadingDialog a singleton class. Lookup the singleton pattern.

  • How to call a instance method without creating the instance of a class

    class ...EXCH_PRD_VERT_NN_MODEL definition
    public section.
      methods CONSTRUCTOR
        importing
          value(I_ALV_RECORDS) type ..../EXCH_VBEL_TT_ALV
          value(I_HEADER) type EDIDC .
      methods QUERY
        importing
          I_IDEX type FLAG
          i_..........
        returning
          value(R_RESULTS) type .../EXCH_VBEL_TT_ALV .
    Both methods are instance methods.
    But in my program i cannot created instance of the class unless i get the results from Query.
    I proposed that Query must be static, and once we get results we can create object of the class by pasing the result table which we get from method query.
    But i must not change the method Query to a static method.
    Is there any way out other than making method Query as static ?
    Regards.

    You can't execute any instance method without creating instance of the class.
    In your scenario, if you don't want to process your method of your class, you can check the instance has been created or not.
    Like:
    IF IT_QUERY IS NOT INITIAL.
      CRATE OBJECT O_QUERY EXPORTING......
    ENDIF.
    IF O_QUERY IS NOT INITIAL.
    CALL METHOD O_QUERY->QUERY EXPORTING....
    ENDIF.
    Regards,
    Naimesh Patel

  • Class methods vs. Instance methods

    When shall we use class methods instead of instance methods , and vice versa?
    By going through the Java Tutorial, it only says the following.
    A common use for static methods is to access static fields....
    I am definitely sure that class methods aren't just exist for accessing static fields of a class.
    PS. I understand that instance methods belong to the object that is instantiated and class methods belong to the class itself.

    Jay-K wrote:
    JoachimSauer wrote:
    P.S.: I wouldn't call them "class methods". They are called static methods in Java. It helps to stay with the common, widely-used terminology.Thanks, its good to know what the norms are.
    but i wonder why the Java Tutorial states it clearly "Class Methods" over here [http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html|http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html]
    Because strictly speaking that's what they are. They belong to classes, rather than instances of classes. The world-at-large, though, has found that term to be a bit ambiguous, especially when discussing fields - it's not uncommon to see instance variables referred to as "class variables" by newbies - so it's kind-of self-corrected.

  • Objects and instance methods for JSP?

    I've been looking through the JSP 2.0 specification and, while I'm extremely impressed with the improvements in this version, I'm also disappointed to see that everything still boils down to statically bound methods.
    What I mean by this is that the template part of a JSP is like an anonomously named static method associated with the JSP class. The new tag-files in JSP 2.0 are terrific, but they also have this same kind of static binding.
    As far as I know, only JPlates (www.jplates.com) allows you to develop web applications using actual instances of classes that have instance methods for expressing the template parts. Are there any other template processing systems that support real object-oriented development of dynamic content-generation applications?

    By an amazing coincidence, the domain name jplates.com is registered to a Daniel Jacobs and your user name is djacobs. What are the odds of that?
    If you're going to plant commercials, you need to disguise them better than this.

  • How can I use instance methods created with HashMap

    class Template
    static HashMap customer;
    a few methods created various customer
    public static display() //to display a particular customer information among i've created above
                 String objectName,currentObjectName;
              Customer customer;
              Scanner scan=new Scanner(System.in);
              System.out.print("Please enter the customer name");
              objectName=scan.nextLine();
              Iterator iteratorForCustomer=CustomerMap.entrySet().iterator();
              Map.Entry customerEntry=(Map.Entry)iteratorForCustomer.next();
             while(iteratorForCustomer.hasNext())
                    customerEntry=(Map.Entry)iteratorForCustomer.next();
                    if(objectName.equals((String)customerEntry.getValue()))
              System.out.println("Name : " +customer.getName()); //I'm trying to reference to an instance method getName() here but i can't do that .
    }The problem is I've created as many as I want and later in the program I tried to redisplay a particular customer information based on the input (objectName). User type in the objectName and I tried to look for a particular customer Object in the HashMap and display only the relevant customer information. Is there any way to do it ? Thanks everyone in advance.

    Peter__Lawrey wrote:
    use the get method
    [http://www.google.co.uk/search?q=map+tutorial+java]
    [http://java.sun.com/docs/books/tutorial/collections/interfaces/map.html]
    And then either look at a generics tutorial, or, if you're stuck on a pre-1.5 version of Java, find out about casting

  • Calling Instance Method in a Global Class

    Hi All,
    Please can you tell me how to call a instance method created in a global class in different program.
    This is the code which I have written,
    data: g_cl type ref to <global class>.
    call method g_cl -> <method name>
    I am not able to create Create object <object>.
    It is throwing the error message " Instance class cannot be called outside...."
    Please can anybody help me..
    *Text deleted by moderator*
    Thanks
    Sushmitha

    Hi susmitha,
    1.
    data: g_cl type ref to <global class>.
    2.
    Create object <object>.
    3.
    call method g_cl -> <method name>.
    if still you are getting error.
    then first check that method level and visibility in se24.
    1.if  level is static you can not call it threw object.
    2. if visibility is protected or private then you can not  call it directly.
    If still you are facing same problem please paste the in this thread so that i can help you better.
    Regards.
    Punit
    Edited by: Punit Singh on Nov 3, 2008 11:54 AM

  • How to call Instance Methods and set property values in BAPI?

    In Project systems, for the three business objects viz.
    Network, ProjectDefinition and WBS, there are two kinds of methods which are available : class methods and instance methods. We have tried calling some instance methods, for instance, BAPI_PROJECTDEF_GETDETAIL to get details pertaining to a project. While importing this BAPI, it shows two elements for mapping i.e. Current Internal Project(string) and Current External Project(string). We supplied these values for an existing project. Upon running this call through an XML client at our end, it
    returned an error "Module Unknown Exception". This general message is present on every instance method thus far. Upon searching in BAPI Explorer for Project System->ProjectDefinition->GetDetail, we found that this BAPI didn't take any input parameter.
    Following message was displayed in BAPI Exlorer for this BAPI:
    "... Obligatory import parameters are the external and internal keys CURRENTEXTERNALPROJE and CURRENTINTERNALPROJE of the project definition.The system reads parameters contained in the structure
    BAPI_PROJECT_DEFINITION_EX ..."
    i) How to supply the values of Obligatory import parameters.
    ii) What are the possible causes of this exception.
    iii) How to call an instance method. We are using same mechanism for calling class as well as instance methods so far, we have been to call only class level methods successfully. Is there anything special that we
    need to do to call instance methods.

    Hi,
    what version is the SAP PS running?  If WebAs or higher,  create an inbound synch interface containing your two parameters in the request structure and as many as you require in your response structure.  Generate an Inbound ABAP proxy, where you can plug in some code, i.e. create and instantiate an object of the required type and make the call to the BAPI.
    If SAP PS on lower than WebAs, then create a wrapper function module and make it RFC enabled.  Then plug your code in here and do the same thing.
    Watch out for commits!
    Cheers,
    Mark

  • Synchronized Instance Methods in Singleton Class

    If I've a TransactionManager class that's a singleton; meaning one manager handling clients' transaction requests, do I need to synchronize all of the instance methods within that singleton class?
    My understanding is that I should; otherwise, there's a chance of data corruption when one thread tries to update, but another thread tries to delete the same record at the same time.

    Let's say that you have a singleton that is handling
    the printing in a desktop application. This could be
    time consuming and it will not probably be used too
    often. What's time consuming about instantiating the object?
    On the other hand you could not say that it
    will never be used.Exactly. If that were so, why write it?
    In a web application, response time is much more
    important than initialization time (which can be
    easily ignored). Never ignored. It's just a question of when you want to pay.
    Web app as opposed to desktop app? Does response time not matter for them?
    In this case, of course, eager
    initialization makes much more sense.I'm arguing that eager initialization always makes more sense. Lazy for singletons ought to be the exception, not the norm.
    %

  • Private instance method

    I want to have a private instance method in my application that changes the values of some variables. Then I want to use these variables in the main method. Is it possible to do this?
    When I tried to do it, I recieved the following error message:
    non-static variable cannot be accessed in static context
    Can anybody help me?

    import java.util.*;
    public class Test {
      public static void main(String[] args) {
        Test test = new Test();
        test.showData();
        test.setMyString("xyz");
        test.setMyInt(55);
        System.out.println("Main1 - myInt="+test.getMyInt()+", myString="+test.getMyString());
        test.mungeData();
        System.out.println("Main2 - myInt="+test.getMyInt()+", myString="+test.getMyString());
      private int myInt = 3;
      private String myString = "abc";
      public Test() { }
      public String getMyString() { return myString; }
      public void setMyString(String s) { myString = s; }
      public int getMyInt() { return myInt; }
      public void setMyInt(int i) { myInt = i; }
      public void mungeData() { myInt++; myString+="x"; }
      public void showData() { System.out.println("Test - myInt="+myInt+", myString="+myString); }
    }

Maybe you are looking for

  • MacBook and TC trouble connecting wirelessly to PC network

    Linksys modem on a PC accepted my new MacBook just fine. Tried to install the TC (500GB) today. AirPort utility recognized the TC once, but when I tried to add it to the established network I apparently failed somewhere and the TC went away. Now AirP

  • Down Payment from Purchase order

    Is it possible to create a down payment document automatically for a particular vendor when the PO or PR is created.Is there any vendor specific settings that has to be done

  • Deleting songs while using the icloud and ios 6 system

    I just updated to the ios6 system and have been using the icloud. Since downloading the ios 6 system I can't delete songs off of my ipod. Suggestions?

  • Create a user and use  the objects of another Shema

    Hi all oracle`s gurus i need a little help ..... i, create a shema named "a" that the owner is user_dba and here there are all objects of the aplication but i want all other users of the app can use those objects; the users are created in the databas

  • Power query on Excel 2007?

    Hi all of you, Would it be possible to install Microsoft Power Query on Office 2007 installation?  Thanks for any input or hint,