Worklight: Performance of calling java static method vs object creation - java

I need suggestions either I make custom java method as static OR accessing via java object from an Adapter?
My scenario is: thousands of users are making transactions and each user is accessing the same method again & again and just changing some values specific to that user or transaction.
Now if I am making them as static methods then will it cause problems for users, as we know the adapter call is asynchronous....so if multiple users calling same method at the same time then will it cause problem is returning different values to each other?
Or if i access all custom java methods via first declaring that class object and then accessing methods, providing parameters....so in this way when multiple users access the same method at the same time then they will get proper/relevant data?
From performance point of view which approach is good and does static method approach bring wrong data to users.....one user's data to another, and others to another person.
thanks
Abdul Ahad
------------ my code is like---
java code:
public static String getBalanceSummaries(String userAct){
String replyMsg="";
try {
replyMsg = getBalanceStatementfromMQ(userAct);
}catch(Exception e) {}
return replyMsg;
}
-----WL Adapter code:------
function showAllBalace(userActNo){
return{
result: com.my.package.getBalanceSummaries(userActNo)
};
}

I believe that you are confusing static methods with static fields. Static methods are just code that is not associated with any specific instance of an object - basically any method that is not using this or super references could be a candidate for being static, provided that they are not overriding another method and are not intended to be overridden. Static methods do not have any additional concerns w.r.t. multithreading when compared to "normal" methods.
Static fields, on the other hand, are by definition shared among all threads and access to them should be protected as with any shared resource. Any method using a static field, regardless of whether the method itself is static or not, should be inspected for concurrency issues.
As far as performance goes, there is anecdotal evidence that static methods may provide performance improvements when compared with normal virtual methods, but quite honestly I would not worry about it until a profiler tells me to. Premature optimization is the root of all evil...

Related

If memory can be saved by using static methods, why aren't all methods declared as static (instead of using instance methods)?

In Java, a static method is used to save memory because there is no need to create an object to call static methods. And we need to create an object when we have to call instance methods; so whenever we create an object it takes memory. We know that, in any project, maximum methods are non-static.
Why then do we not declare all methods as static, instead of having instance methods be the norm, in order to save memory in a project?
Some methods — probably most — need information in order to do their work. You have to store that information somewhere.
If all of your methods are static, that doesn't magically make the need for that information go away. And if you need the information, you need to store it, so you can pass it into the static method so the method can do its work. So there's no memory savings achieved by using only static methods: You're going to store that information somewhere.
In Java's style of object-oriented programming (and many but not all others), you store that information with (conceptually) the functions that operate on it (instance methods): An object.
For methods that don't need information, or that reasonably should receive all of the information they operate on via parameters, we use static methods.

Java: Using Static Methods for repeated code sections

So I'm learning Java (gasp bet you could've never guessed that), and today I'm focused heavily on making sure that I'm using static methods properly.
My big practice program right now is an account manager program, that I tweak and add to as I learn more and more concepts. One component of it is printing out a list of all the accounts added to the system. Because this list gets summoned more than once, I created a static method that can be invoked to generate it, and placed it above my main method in the code.
My question is: should I do this? Is it a good idea/good programming etiquette to create methods like this for repetitive sections of code? And if the answer to both of those is yes, should I make it a static method?
Here's the code for the static method I'm talking about:
/**
* accountList() method displays a list of all accounts currently loaded into the program
*/
public static void accountList(){
System.out.println(" ACCOUNT LIST");
System.out.println("NUMBER INFORMATION");
for(int num = 0; num < accountArray.size(); num++){
System.out.println(" " + (num + 1) + " " + accountArray.get(num).getAccountName()
+ " : " + moneyFormat.format(accountArray.get(num).getValue()) + " "
+ accountArray.get(num).getCurrencyType());
}
listMax = accountArray.size();
}
Then below this would be my main() method, and periodically within my main would be the invocation of this method to generate an account list:
public static void main(String[] args){
accountList(); //example of how I would invoke this method
}
So, do I have this figured out properly? Am I using this correctly? Thanks.
PS. My accountList() method is in the same class as my main() method, which is why there's no class name before it. That's also why I'm asking, because I know one of the main purposes of the term "static" is that it would be easily accessible from another class, so I'm not sure if it needs to be static if it's in this same class.
Is it a good idea/good programming etiquette to create methods like this for repetitive sections of code?
Having many small methods in stead of fewer large methods is a good practice in terms of maintainability and re-usability.
should I make it a static method?
Static methods are used when they do not depend on state of some particular instance of the class. It is in general avoided since subtype polymorphism is not available for static methods (they can't be overridden). Small utility methods are made static (like Math.sqrt or System.currentTimeMillis()).
Note: (Optional)
When you define methods to re-use the code, the most important aspect is the contract that the method is supposed to fulfill. So the methods should communicate with each other using arguments and return values for predictable behavior. Mutating state of class fields (or even worse static fields) is generally considered a bad idea (you have to do it though sometimes).
You could improve your method to something like following.
public static void printAllAccounts(List<Account> accountList) {
// Your code ...
}
This method specifies which accounts to print, and does not depend on state.
It would be even better if you can delegate it to another class and make it a non static behavior. That way if you come up with better way of printing all accounts, you can replace the behavior without touching this method.
Hope this helps.
Good luck.
Don't repeat yourself (DRY) is a widely accepted principle and good practice, and creating methods for code that would otherwise be duplicated is the simplest and most obvious form for this.
(In some languages/contexts people hint at the potential overhead of a method invocation and its impact on performance. In fact, inlining methods is a common optimization that compilers do. But modern compilers (and particularly, the Just-In-Time-Compiler of the Java Virtual Machine) do this automatically when it is appropriate)
Whether helper methods should be static has already been discussed elsewhere.
My rule of thumb here is: Whenever a method can be static, then it should be static.
A more differentiated view: When a method does not modify instance fields (that is, when it does does not operate on a mutable state), but instead only operates on its arguments and returns a result (and is a "function", in that sense), and when it should not be involved in any form of polymorphism (meaning that it should not be overloaded), then it should usually be made static. (One might have to take aspects of unit testing into account here, but that might lead too far now)
Concerning your specific example:
You have a different problem here: The accountArray obviously is a static field, as well as the listMax variable. And static (non-final, mutable) fields are usually a horrible idea. You should definitely review this, and try to make sure that you do not have static fields that describe a state.
If you did this, your method could still be static, and receive the accountArray as a parameter:
public static void accountList(List<Account> accountArray){
System.out.println(" ACCOUNT LIST");
...
}
However, in this form, it would violate another best practice, namely the Separation of Concerns. The method does two things:
it creates a string representation of the accounts
it prints this string to the console
You could then split this into two or three other methods. Depending on the indented usage, these could, for example, be
public static String createAccountInfoString(List<Account> accounts) {...}
public static void printAccountInfo(List<Account> accounts, PrintStream ps) {
ps.println(createAccountInfoString(accounts));
}
public static void printAccountInfo(List<Account> accounts) {
printAccountInfo(accounts, System.out);
}
(note that the method names indicate what the methods do. A method name like accountList doesn't tell you anything!).
However, as others have pointed out: Overusing static methods and passing around the information may be a sign of not properly using object-oriented concepts. You did not precisely describe what you are going to model there. But based on the keywords, you might want to consider encapsulating the account list in a class, like a class AccountList, that, among others, offers a method to print an account list to a PrintStream like System.out.
Here's what a static method is. A static method from the same class, you can just call without the class name, but a static method from another class, you would have to call with the class name. For example, if you have a static method called method1 in a class called Class1, and you're trying to call the method in a different class called Class2, you would have to call the method like this:
Class1.method1();
If you just use method1(), it would show up as an error, and it'll tell you that it can't find the method, because it only searches the class you're in for the method, and it doesn't find it. You would have to put the class name, Class1, so it knows to go search for the method in Class1, and not the class you're in.
As for whether you should use a static method or not, that depends, really, on your preference. Do you know the different between a static method, and a non-static one? I'll just gives you the basics for now. If you have more questions, you can ask.
Okay. A non-static method can only be called when you make an object out of the class the method is in. This is how you make an object:
(CLASS NAME)(OBJECT NAME) = new (CONSTRUCTOR NAME)();
The constructor's name is the same as the class name. And when you call the method, you would put (OBJECT NAME).METHOD NAME(); to call it. As for a static method, I already told you how you can call it. So. Anymore questions?
The use of static methods is something that could remember procedural programming. In fact, if you use static methods you cannot use OOP principles, like polymorphism.
First of all, it is not good that a method, which aims is to print a list, could change program state. Then, in the future, you may want to change the way the list is printed. Let say, you want to print it in file. How would you change your program to satisfy this new requirement if your ar using a static method?
Try to think more OO, and in the beginning, try to put your code inside a dedicated class (i.e. Printer). Then, you can extract an interface from that class, and finally try to apply some design patterns, like Strategy Pattern or Template Method Pattern.
static members of a class (that is variables, method) are not related/associated to the instance/object of the class. They can be accessed without creating object of the class.
General rule of using static method is - "Ask yourself is the property or method of a class should applicable for all of the instance of the class". If the answer is yes then you may use static member.
Consider the following example -
public class Student{
private int noOfStudent;
.......
}
Now you have a Student type. In this case you may consider to make the noOfStudent property static. Since this is not the property of a Student itself. Because all students of a class should share the same property of noOfStudent.
You can find more explanation here
Hope it will Help.
Thanks a lot.

When to use static method and field?

I know what static is, but just not sure when to use it.
static variable:
I only used it for constant fields. Sometimes there are tens of constants in a class, so using static constants can save lots of memory. Is there any other typical use cases?
static method:
I use it when I make a class about algorithms. For example, a class which provides different sorting algorithms. Is it against OOP design? I think it is better to maintain this way rather than implementing sorting algorithms inside each class that needs to use them. Am I wrong? What are some good use cases?
Also, are there any performance difference between using static and non-static fields/methods?
You are describing cases where you've used static, but this doesn't quite explain fundamentally why you would use static vs non-static - they are more than just keywords for constants and utility methods.
When something is not static (instance), it means that there is an instance of it for each instance of the class. Each one can change independently.
When something is static, it means there is only one copy of it for all instances of the class, so changing it from any location affects all others.
Static variables/methods typically use less memory because there is only one copy of them, regardless of how many instances of the class you have. Statics, when used appropriately, are perfectly fine in object oriented design.
If you have a method/variable that you only need one instance of (e.g. a constant or a utility method), then just make it static. Understand though that making a method static means it cannot be overridden. So if you have a method you want to override in a subclass, then don't make it static.
The general rule of thumb is - if you need only one copy of it, make it static. If you need a copy per instance, then make it non static.
Is there any other typical use cases?
Global Variables
Is it against OOP design?
Not exaclty, the point is that static methods are stateless since you don't need a particular instance of a class. My favorite approach is for utility methods (like Apache Commons). But you may be aware that some methods may be better placed as class members instead of static.
Also static methods can make class testability harder once you can't override these methods or replace by mock implementation.
Performance difference ?
There's a performance Android recommendation from Google that says "prefer static over virtual":
http://developer.android.com/training/articles/perf-tips.html#PreferStatic
I'm not sure it's true for JVM since Android uses a different VM, but it makes sense given the reasons the link points out:
If you don't need to access an object's fields, make your method static. Invocations will be about 15%-20% faster. It's also good practice, because you can tell from the method signature that calling the method can't alter the object's state."
My personal rule of thumb is that static things are "just hanging out there". They are things that (disclaimer, not entirely true) are global, but make sense to include with this one particular class.
Static fields are good if you find yourself loading some heavyweight objects repeatedly. For instance, the project I'm working on now has a toggle between two images. These are static fields that are loaded with the application and kept in memory, rather than reloading them every time and letting GC take care of the mess.
Apart from very specific situations, I use static (and final) variables for constants only. It's a totally valid to use them, of course.
I tend to avoid static utility methods, because they make it harder to write unit tests for the code (mocking the results of the method invocation). When you start developing Test Driven way, this issue becomes quite apparent. I prefer using dependency injection and singleton beans (though it depends on your needs and situation).
Static variables belong to a class, hence shared by all the objects, so memory usage is less if you really want the varible to be shared. If you declare the variable as public and static, then it is globally available for everyone.
Static methods are generally the utility methods, depending on the access modifier, those can be used within a class or across the classes. Static utility class will help to reduce the memory usage again because you need not to create the object to call those methods.
The static field has one value among all objects and they call it Class member also because it's related to the class.
You can use static filed as a utility.
an example just Assume we need to know how many instances we have :
class Counter
public class Counter {
public static int instanceCount ;
public Counter()
{
instanceCount++;
}
public int getInstanceCount()
{
return instanceCount;
}
}
After creating two instances of Counter Class. But they share the same instanceCount field because it's a static field so the value of instanceCount will become the same in firstCounter and secondCounter .
Class main
Counter firstCounter = new Counter();
// will print 1
System.out.println(co.getInstanceCount());
// will print 2
Counter secondCounter = new Counter();
System.out.println(co1.getInstanceCount());

Static vs Instance for Global state variable

I have a global boolean variable which I use to disable all trading in my financial trading system.
I disable trading if there is any uncaught exception or a variety of other conditions (e.g. no money in account).
Should this variable be static or an instance variable? If its an instance I will need to add it to constructors of loads of classes...Not sure if its worth the hassle.
Thxs.
If it's an instance, then you probably want it to be a Singleton, and you'll provide a public static getter (or a factory, or DI if you care about testing).
If you access it from multiple threads, then it'd better be an AtomicBoolean in both cases.
Throughout your entire career, the number of times that you will have a valid use for a global variable will be countable in the fingers of one hand. So, any given time you are faced with a "to global or not to global" decision, most chances (by far) are that the correct answer is NOT. As a matter of fact, unless you are writing operating system kernels and the like, the rule of thumb should be "do not, under any circumstances, make any variable whatsoever, anywhere, anytime, global."
Note that wrapping access to a global variable in a global (static) method is just fooling yourself: it is still just a global variable. Global methods are only okay if they are stateless.
The link provided by #HermantMetalia is a good read: Why are static variables considered evil.
In your case, what you need is probably some kind of "Manager" object, a reference to which you pass as a construction time parameter to all of your major logic objects, which, among other things, contains a property called "isTradingAllowed" or something like that, so that anyone interested in this piece of information can query it.
I'd put it in a static field. But prefer to make it an AtomicBoolean to prevent threading issues :-)
public class TradeMaster {
private static final AtomicBoolean TRADING_ALLOWED = new AtomicBoolean(true);
public static void stopTrading() {
TRADING_ALLOWED.set(false);
}
public static boolean isTradingAllowed() {
return TRADING_ALLOWED.get();
}
}
Static Pros:
No need to pass references to instance to every class which will be using this
Static Cons:
May lead to difficult in testing - I think it should be fairly easy to test a static variable if you set the state of the variable before and after the test (assuming the tests are not running concurrently).
Conclusion:
I think the choice here depends on what your view of testing static variables is...For this simple case of one variable managing the state I really cant see the problem with using static. On the otherhand...its not really that hard to pass an instance to the constructors of the dependent classes so you dont really have any downside when using the instance approach.
It should be static since it will be shared by all the instances of
this class.
It should be static since you dont want to have a separate variable for all the objects.
Given that I would suggest that you read some good resources for static variable usage they work like charm unless you mess them..
If you want to make a variable constant for the class irrespective of how many instances are creted then use static method. But if the variable may change depending on the use by different instance of class then use instance variable.
Example
*
Here is an example that might clarify the situation. Imagine that you
are creating a game based on the movie 101 Dalmations. As part of that
project, you create a Dalmation class to handle animating the various
Dalmations. The class would need instance (non-static) variables to
keep track of data that is specific to each Dalmation: what its name
is, how many spots it has, etc..
*
But you also need to be able to keep track of how many Dalmations have
been created so you don't go over 101. That can't be an instance
variable because it has to be independent of specific Dalmations. For
example, if you haven't created any Dalmations, then this variable has
to be able to store zero. Only static variables exist before objects
are created. That is what static variables are for - data that applies
to something that is beyond the scope of a specific instance of the
class.

A member variable's hashCode() value is different

There's a piece of code that looks like this. The problem is that during bootup, 2 initialization takes place. (1) Some method does a reflection on ForumRepository & performs a newInstance() purely to invoke #setCacheEngine. (2) Another method following that invokes #start(). I am noticing that the hashCode of the #cache member variable is different sometimes in some weird scenarios. Since only 1 piece of code invokes #setCacheEngine, how can the hashCode change during runtime (I am assuming that a different instance will have a different hashCode). Is there a bug here somewhere ?
public class ForumRepository implements Cacheable
{
private static CacheEngine cache;
private static ForumRepository instance;
public void setCacheEngine(CacheEngine engine) { cache = engine; }
public synchronized static void start()
{
instance = new ForumRepository();
}
public synchronized static void addForum( ... )
{
cache.add( .. );
System.out.println( cache.hashCode() );
// snipped
}
public synchronized static void getForum( ... )
{
... cache.get( .. );
System.out.println( cache.hashCode() );
// snipped
}
}
The whole system is wired up & initialized in the init method of a servlet.
And the init() method looks like this conceptually:
// create an instance of the DefaultCacheEngine
cache = (CacheEngine)Class.forName( "com..DefaultCacheEngine" ).newInstance();
cache.init();
// init the ForumRepository's static member
Object o = Class.forName( "com.jforum....ForumRepository" ).newInstance();
if( o instanceof Cacheable )
((Cacheable)o).setCacheEngine(cache);
// Now start the ForumRepository
ForumRepository.start();
UPDATE I didn't write this code. It is taken from jforum
UPDATE 2 Solution found. I added a separate comment below describing the cause of the problem. Thanks to everyone.
You're going to have to give WAY more information than this, but CacheEngine is probably a mutable data type, and worse, it may even be shared by others. Depending on how CacheEngine defines its hashCode(), this could very well lead to aForumRepository seeing various different hash codes from its cache.
It's perfectly fine for the same object, if it's mutable, to change its hashCode() over a period of time, as long as it's done in a consistent manner (which is another topic altogether).
See also
Object.hashCode() -- make sure you understand the implications of the contract
On cache being static
More information has resurfaced, and we now know that the object in question, while mutable, does not #Override hashCode(). However, there seems to be a serious issue in design in making cache a static field of ForumRepository class, with a non-static "setter" setCacheEngine (which looks to be specified by Cacheable).
This means that there is only incarnation of cache, no matter how many ForumRepository instances are created! In a way, all instances of ForumRepository are "sharing" the same cache!
JLS 8.3.1.1 static Fields
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized.
I think it's important to step back right now and ask these questions:
Does cache need to be static? Is this intended?
Should instances of ForumRepository have their own cache?
... or should they all "share" the same cache?
How many instances of ForumRepository will be created?
Putting pros and cons of the design pattern aside, should ForumRepository be a singleton?
How many times can setCacheEngine be called on a ForumRepository object?
Would it benefit from a defensive mechanism of throwing IllegalStateException if it's called more than once?
The best recommendations would depend on the answers to the above questions. The third bullet point is something that is immediately actionable, and would reveal if setCacheEngine is getting invoked multiple times. Even if they're only invoked once for each ForumRepository instance, it's still effectively a multiple "set" in the current state of affairss, since there's only one cache.
A static field with a non-static setter is a design decision that needs to be thoroughly reexamined.
are you sure the ForumRepository classes that you are comparing are the same. if you are doing newInstance you might have a weird classloader issue.
Mutable objects with hashCode implementations based on mutable state are almost always a bad idea. For example, they behave very strangely in hash-based collections -- if you insert such an object into a HashSet and then mutate it, the contains method won't be able to find it anymore.
Objects that are naturally distinguished by their identity should not override equals and hashCode at all. If you override hashCode based on state, that state should be immutable. Examples are String and the boxing types. Those are often referred to as "value classes", because their identity has no significance -- it is meaningless to distinguish between multiple instances of new Integer(42).
The thing that puzzles me about this question is this:
Why are you looking at the hashcode of a CacheEngine instance?
It seems that your code is putting Forum objects into a cache and getting them back. As such, it makes sense to look at the hashcode values for the Forum instances. But the hashcode of the cache itself would appear to be entirely irrelevant.
Having said that, if the DefaultCacheEngine class inherits its implementation of hashcode from java.lang.Object then the value returned by the method is the "identity" hashcode, and this cannot change over the lifetime of an object. If it does appear to change, this means that you are now looking at a different instance of the DefaultCacheEngine class.
I've solved my problem and I would like to share with you what I've learnt or discovered.
Root cause of the bug
The jforum.war webapp was being loaded twice by Tomcat 6.x, via two different virtual hosts. So yes, the CacheEngine was displaying two different hashCodes because they were loaded up in separate webapp classloaders.
Solution
The quick fix for me was to limit the invocation of the servlets in jforum.war via one specific virtual host address.

Categories

Resources