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

Similar Messages

  • Why there should not be many static methods.

    Why a java class should not have many static methods.How is memory managed in case of static methods.
    If a Utility class has static methods then we can use methods directly by class name but if we do not make the methods static then we can acess methods using object.How does it make the difference.I know that there remains a single copy of class variables/methods.But i want to know how class memory is managed and garbage collected.

    shobhit123 wrote:
    Why a java class should not have many static methods.How is memory managed in case of static methods.
    If a Utility class has static methods then we can use methods directly by class name but if we do not make the methods static then we can acess methods using object.How does it make the difference.I know that there remains a single copy of class variables/methods.But i want to know how class memory is managed and garbage collected.The reason to discourage static methods is stylistic rather than technical. It encourages object oriented thinking.
    Each loaded class is represented by a Class object, and associated with that it a block of memory for static fields. As with all such storage this block is, as viewed from code, rather like an array with one, or in the case of double or long values, two slots per field.
    Because the class loader maintains a map from FQN to Class this storage is only released if the class loader that loaded it becomes unreachable, which happens only in situations like the un-deployment of a web application or EJB.
    Local variables for static methods are allocated in a stack frame, just as with instance methods. There's really no significant difference there.

  • Which Function Should i use for static values for a an array[] in BPM 11g.

    Hi Experts,
    Please throw some light on this..
    I've a requirement which is bugging me..
    How do i assign a static value to a array in BPM11g in script activity. What exactly function do i need to use to assign a Static value for an Array []
    I been doing like taking the business object as a Array thats fine. But how can i set a static value in BPM 11g.
    Iam using BPM 11.1.1.6 version..
    Regards,
    Pavan

    Hi Pavan,
    Here's one approach, but it assumes you're comfortable with XSDs and XML.
    Know this is light on detail, but without knowing what your array looks like it's the best I can do. Here's what you'd do from a high level:
    1. Create an XSD that defines the structure of your array.
    2. Create the XML that represents the static item you want to add to the array.
    3. Create a process variable based on the XSD that defined the array.
    4. Add a Script activity.
    5. Open the "Implementation" tab -> click "Data Associations".
    6. On the right, expand the folder under your process -> drag the XML icon in the upper right corner on the array variable -> paste your XML into the XML literal panel.
    Hope this gets you going,
    Dan

  • GUI component services: Use static methods or query direct parent?

    Hi
    I have a large panel (covers most of the window) that contains a square grid of smaller panels. Each smaller panel contains a square grid of buttons. For instance, PnlGrid contains a few PnlGridSections and each PnlGridSection contains some BtnGrids.
    There is certain funtionality that must be available to BtnGrid objects but I am not sure if I should simply provide static methods in PnlGrid and access them from everywhere else in the code or have BtnGrid ask its direct parent (i.e. PnlGridSection) to deal with it.
    For instance, I am currently using a static method, PnlGrid.getIconCache(), to retrieve a reference to the icon cache and locate the texture I need from within a BtnGrid. Would it more correct to retrieve a pointer to the direct parent of this button (i.e. PnlGridSection) and have him return the pointer to the icon cache?
    Thanks

    Hi
    I have a large panel (covers most of the window) that contains a square grid of smaller panels. Each smaller panel contains a square grid of buttons. For instance, PnlGrid contains a few PnlGridSections and each PnlGridSection contains some BtnGrids.
    There is certain funtionality that must be available to BtnGrid objects but I am not sure if I should simply provide static methods in PnlGrid and access them from everywhere else in the code or have BtnGrid ask its direct parent (i.e. PnlGridSection) to deal with it.
    For instance, I am currently using a static method, PnlGrid.getIconCache(), to retrieve a reference to the icon cache and locate the texture I need from within a BtnGrid. Would it more correct to retrieve a pointer to the direct parent of this button (i.e. PnlGridSection) and have him return the pointer to the icon cache?
    Thanks

  • What is the use of private static method/variable?

    Hi All,
    I have read lots of books and tried lots of things but still not very clear on the
    topic above.
    When exactly do we HAVE to use private static methods?
    private implies its only for class, cannot be accessed outside.
    But then static means, it can be accessed giving classname.method.
    They seem to be contradicting each other.
    Any examples explaining the exact behaviour will be well appreciated.
    Thanks,
    Chandra Mohan

    Static doesn't really "mean" that the method/field is intended for use outside the class - that is exactly what the access modifier is for.
    Static implies that it is for use in relation to the class itself, as opposed to an instance of the class.
    One good example of a private static method would be a utility method that is (only) invoked by other (possibly public) static methods; it is not required outside the class (indeed, it might be dangerous to expose the method) but it must be called from another static method so it, in turn, must be static.
    Hope this helps.

  • NEED HELP WITH USING STATIC METHOD - PLEASE RESPOND ASAP!

    I am trying to set a value on a class using a static method. I have defined a servlet attribute (let's call it myAttribute) on my webserver. I have a serlvet (let's call it myServlet) that has an init() method. I have modified this init() method to retrieve the attribute value (myAttribute). I need to make this attribute value accessible in another class (let's call it myOtherClass), so my question revolves around not knowing how to set this attribute value on my other class using a static method (let's call it setMyStuff()). I want to be able to make a call to the static method setMyStuff() with the value of my servlet attribute. I dont know enough about static member variables and methods. I need to know what to do in my init() method. I need to know what else I need to do in myServlet and also what all I need in the other class as well. I feel like a lot of my problems revolve around not knowing the proper syntax as well.
    Please reply soon!!! Thanks in advance.

    class a
    private static String aa = "";
    public static setVar (String var)
    aa = var;
    class b
    public void init()
    a.aa = "try";
    public static void main(String b[])
    b myB = new b ();
    b.init();
    hope this help;
    bye _drag                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • What time should I use clone method?

    Hi everyone:
    There is a problem puzzled me all the time. You know,If I want to use a object I could use the code:
    Class A=new Class(); I get a object A so I can use it. But there is a method called "clone".It's function is copy a object.But Why jdk have this method.Is there any useful ?
    I mean that what situation should I use the "clone " method?
    Thks!

    a regular clone copies all members of an object by reference. You can implement the Clonable interface to provide a clone which makes a 1:1 copy of your object, so no references are copied over. This ensures that the objects don't share the same objects, but do have the exact same content.

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

  • Static method decisions

    Dear all experts,
    I have got some problems understanding when to use static methods or passing the classes through constructor.
    I have got a class which needs to be accessed by several classes and also the classes inside the classes etc....
    Instead of passing classes around, should I just create a single static class which can be accessed by all the classes without needing to instantiate the class?
    I found that, i particularly in doubt when there are classes like "TableParser", "PropertiesReader" etc which some classes deep down in the hierarchy need access to those classes...
    Also, making the class static would it decrease the security of the whole program?? Say if i have got an encrytion class which does all the encrypt and decrypt, if i let it be static, isn't it easier to let people accessing the method? the same applies to properties editor etc??
    Any help would be really appreciated.
    Thx

    thx again jverd... (remember the security question? :)
    )I remember your id, but I didn't recall which thread(s) I had seen it in.
    >
    based on the understanding of what you said, do you
    mean that, if i am only using a class to store or read
    a setting file, it's ok to let it static? (so that all
    classes can access it whenever they like without
    passing the parser class to classes?)Um, again, you're terminology's a little off, so I'm not sure exactly what you mean, and even the description "store or read a seting file" could have a couple of interpretations.
    For example....You read the file once, and the config data it constains is accessible throughout your app and never changes. This might be a candidate for a class that only had static methods, but it would be kind of inflexible. What if later some other part of your app, or some other library that you develop that your app is going to use, wants to get its configuration from a file. In that case, I might want to have a couple instances of that class around. One for the global config that reads one file, and another for the config for that library that might read another file.
    I'd probably not even think about it as "reading a settings file." Rather, I'd see that as two parts: providing config settings to the app via a class, and reading a file to populate that class. The settings would exist independent of the fact that you can populate them from a file.
    I'd think about how I want to use them and decide whether to instantiate the class or use static methods based on that. Separately, I'd think about how this class or an instance of it is gonna get popuated with data from outside the program.
    I might decide to have different instances hold different sets of config data, and therefore use instance (non-static) methods to access the data in each of those instances, but I might register the instances--say by name, or maybe just in a list--and I could use a static method to acess the map or list: Config dbConfig = Config.getConfig("database"); Also, I wouldn't generally make a decsision on whether to use class methods or instance methods based on not having to pass a parameter.
    If you're thinking "I'd like to use static because it's easier. Can I get away with it here," then you're viewing objects as a burden to be avoided, which kind of defeats the purpose of using OO techniques in the first place.

  • Static methods

    Is creating a static method frowned upon in OO development? Is it only a matter of convenience by not having to instantiate?
    Any insight is appreciated.
    --Gregory
    quote: Don't throw away the old bucket until you know whether the new one holds water.

    Regardless of how many objects you have created, there is only 1 copy of the static variables in the memory. Its not just a matter of convenience but is used in certain conditions based on some requirements. A good example would be Singleton. There already is a kind of Singleton class in the standard Java class libraries:
    the Math class. This is a class that is declared final and all methods are declared static, meaning that the class cannot be extended. The purpose of the Math class is to wrap a number of common mathematical functions such as sin and log in a class-like structure, since the Java language does not support functions that are not methods in a class. You can use the same approach to a Singleton pattern, making it a final class. You can�t create any instance of classes like Math, and can only call the static
    methods directly in the existing final class.
    Another approach, suggested by Design Patterns, is to create Singletons using a static method to issue and keep track of instances. To prevent instantiating the class more than once, we make the constructor private so an instance can only be created from within the static method of the class.
    Hope that helps
    &#9824

  • Static Method to calculate ' Average '.

    Hi
    I am wondering which one is preferred?  Static or Instance methods for calculating 'average' (e.g average sales).
    My class lcl_company is having attributes name and sales. which represents name = name of the company, sales = total sales of one company under department: automobiles.
    eg output:
    Department: automobiles.
    name = abc company
    sales = 1000
    name = xyz company
    sales = 2000
    total companies added: 2.
    now i want to calculate the average sales of the companies under department automobiles.
    I prefer using a static method (is it good choice), if not, why instance method. while using the static method, I noticed that i need to stick just with the defined attributes.
    Please advice on calculating average.
    Thank you.

    Hi Pawan,
    There are so many ways,:
    One, as you said, you defined this itab as a attribute of this Object, then you need define another attribute 'AverNum' as public. Of cause, this Object have a method using to calculate the average number, passing the value to public attribute 'AverNum', then you can access this public attribute from outside.
    Another way:  Define this itab as a importing parameter of your average method, same time, this average method have a return parameter. Then you can call this static object method or instance object method from outside, and return your output by return parameter.
    regards,
    Archer

  • Static methods, what for?

    What are static methods for? is there something that is not possible through methods associated with instances (non-static methods) ?

    There are many examples of static mehods in the Java API. For example the Math or the System class. All methods in this classes are static. So you dont have to instantiate the system class. In fact it is even not possible to instantiate the System class. System is final and all Constructors are private.
    Another use for static methods is the access to private static variables.

  • Need some explanations regarding static Method

    Hello,
    I have a code where a class has a static method access by other classes. This not working as I thought and I would like to understand why.
    Here below is the code.
    Here is a class having the static method "test"
    package test;
    public class StaticTest {
        public StaticTest() {
        public static void test (int i){
        while (i < 1000){
            System.out.println("i = " + i );
            i++;
    }Here is the code of another class (Thread) using this static method. This Thread can be initialized with an integrer value that will be passed to the static Method.
    package test;
    public class ThreadTester extends Thread {
        int x;
        public ThreadTester(int i) {
            x=i;
        public void run(){
            StaticTest.test(x);
    }Here is the code starting 2 Thread running in parallel and both are then calling the static method.
    //start 2 thread accessing the static method.
          ThreadTester test1 = new ThreadTester(0);
          ThreadTester test2 = new ThreadTester(200);
          test1.start();
          test2.start();
    ...As the second thread is started with a bigger value I thought that we would only have seen few printouts from the first thread starting by 0 and then printouts starting by 200.
    Here is what I thought regarding the result:
    i = 0
    i = 1
    i = 2
    i = 3
    i = 200 --> startup of the second thread, x in static method is overriden (at least this is what I thought!)
    i = 201
    i = 202
    i = 203
    i = 204
    i = 205
    i = 206
    i = 207
    i = 208
    i = 209
    But the real result is:
    i = 0
    i = 1
    i = 2
    i = 3
    i = 4
    i = 5
    i = 200
    i = 6
    i = 201
    i = 202
    i = 203
    i = 204
    i = 205
    i = 206
    i = 7
    i = 207
    i = 208
    i = 209
    i = 8
    It seems that there is 2 instances running in parallel. I thought that it would'nt be the case with the word "Static".
    Also I don't understand the result because if I use JBuilder in Optimizer mode I can see that there is only one instance of StaticTest object.
    Can anyone here explain me how is that possible?
    Thanks in advance for your help.
    Regards,
    Alain.

    >
    thread test1 creates its own stack and starts incrementing �i� starting at values 0. However, in the middle of incrementing, it gets kicked out by the OS (or JVM) into a �blocked� state to allow other threads to run. BUT before leaving the running state, test1 saves the stack state including the value of �i�.
    >
    Ok, now I understand, but then I have another question.
    What is the difference between the code shown in my first post and the following where we create 2 instances of StaticTest class (which is not static in this case for sure).
    How to decide (while coding) if it is better to use difference instances of class or not?
    package test;
    public class StaticTest {
        public StaticTest() {
        public void test (int i){ //Not static anymore
        while (i < 1000){
            System.out.println("i = " + i );
            i++;
    }We create new instance in the Thread.
    package test;
    public class ThreadTester extends Thread {
        int x;
        public ThreadTester(int i) {
            x=i;
        public void run(){
    StaticTest newInstance = new StaticTest(); //Create a new instance
            newInstance .test(x);
    }Alain

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

  • 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

Maybe you are looking for

  • How can I get/set the vaule of a varibale in the planning function

    Hi All, in the fox I can get the value of a variable using VAR(), but How can I get/set it in a normal planning function? any proposal would be very appreciated.

  • Download internal table data to Excel in background

    Hi all ,   Can anyone tell that how i can download internal table data into Excel sheet  in Backgroud Mode . I used both fun mod  ws and gui download but these are not working in background mod . Please help  issue is urgent . Answer is rewarded  by

  • I keep getting an error message that Adobe reader has stopped working.

    I have re-booted, I have un-installed and re-installed andI still can't open a PDF attachment nor can I change a Word doc into a PDF.

  • Can't find an email I see in Spotlight.  Ideas?

    I see an old email in Spotlight that I want to get to.  I can't find it searching in mail, or in Finder.  Any ideas here?  I don't understand why I see the full text of an email thread in Spotlight that seems to be missing elsewhere....  Using 10.9.2

  • Video/Audio out of sync

    We have begun to notice a problem in streaming long videos over an hour in mp4 format. Any videos we stream over an hour the audio gets ahead of the video and after an hour you can notice it pretty bad. We have a couple of videos that are actually 4