Android static class vs non-static class memory performance - java

I've created a class which was static first, this class does not persist state (does not keep context or any variables) is just a list of functions.
But the class is not very used in the app so I decided to make class instantiable.
Why?
Because I think an instantiable class would use less memory as it is not available during the whole app life cycle.
Is this right?
A static class uses more memory than a non-static class?
Thank you

I think you've misunderstood how classes work. Any kind of class is "available" throughout the lifetime of the app. Memory used for the class itself (the methods etc) is very different to memory used by instances. Unless you actually create an instance of the class, it's irrelevant. And even static classes can be instantiated - it's just that they don't maintain an implicit reference to an instance of the enclosing class.
If your class doesn't actually require an implicit reference (i.e. it doesn't use it) then make it a static nested class - or pull it out as a top-level class anyway. (Nested classes can be a pain sometimes - the rules around top-level classes are simpler.)

A static class as such doesn't use more memory than a non static one. All classes are always available in an application - you can always use a static class or create an instance of a non static one.
If you have only methods in your class (which are of a helper method types) a static class is more convenient to use (no need to create an instance) and won't affect your memory usage.

Related

Do Java classes have an instance on machine (JVM) level if they contain only static methods and fields?

Do Java classes have an instance on machine (JVM) level if they contain only static methods and fields?
And if yes, what are the effects of static methods and fields when doing multithreading? Any rules of thumb?
Yes, for each loaded class in the JVM there is an instance of java.lang.Class. It does not matter whether they only contain static methods/fields or instance methods/fields as well.
And this does not have any extra impact on multi-threading beyond what instance fields and methods already have. That is, as long as you realise that the value of a static field is shared between all instances.
If you want to synchronize, you need to synchronize on the java.lang.Class instance for the class (or if the method is a static method inside said class, it can have the 'synchronized' modifier on the static method to have the same effect as synchronizing on the java.lang.Class instance for the class).
One extra thing to note is that a class with the same name can be loaded by more than one classloader at the same time in the JVM- hence classes in Java are not uniquely identifier by their fully-qualified name, instead they are uniquely identifier by the combination of java.lang.ClassLoader instance used to load the class, and the fully-qualified name.
Static methods and variables are at the class level in Java, not instance level.
All shared, writable state needs to be synchronized and thread safe, regardless of static or instance.
There are no such thing as "static classes" in java. There are inner static classes, but i presume that your question its not about this type of classes.
Classes are loaded once per classloader not per Virtual Machine, this is an important diference, for example applications server like tomcat have different classloaders per application deployed, this way each application is independent (not completely independent, but better than nothing).
The effects for multithreading are the effects of shared data structures in multithreading, nothing special in java. There are a lot of books in this subject like http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601 (centered in java) or http://pragprog.com/book/pb7con/seven-concurrency-models-in-seven-weeks (that explain difference concurrency models, really interesting book)
Yes, a class with static fields and methods has exactly one instance, which is accessed through a static call.
If you use static methods, the variables declared within the method are isolated and don't need to be synchronized (the same as in C#: C# : What if a static method is called from multiple threads?).
But when your classes have static variables and you access them within a static method, there is a trade off: When doing multithreading, the access to the static variables must be synchronized. That's the reason why the singleton pattern doesn't work as good as some believe: Instantiation costs, even more if it's only singlethreaded.
Rules of thumb? Static methods with no static class variables are always good. But static classes with variables can become very evil when doing multithreading. Therefore beware of static bottlenecks!

Is a static class a singleton? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between static class and singleton pattern?
I was wondering,
Would a class such as Java's Math class, where all methods are static be considered a singleton? Or does a singleton have to have an instance, eg: Math.getInstance().abs(...) to qualify as a singleton?
Thanks
Having just static methods in a class does not qualify it being a Singleton, as you can still make as many instances of that class, if you have a public constructor in it.
For a class to qualify as Singleton, it should have private constructor, so that it can't be instantiated from outside the class, and have a static factory that returns the same instance everytime invoked.
If you really mean static class, then first of all, you can't have your top-level class as static. You can only have static nested class, in which case you don't need to create any instance of that class, but you can and you can create multiple instances and hence it as not Singleton.
Also, the class you mentioned - java.lang.Math, is not a static class. You should see the documentation of that.
Static classes in Java are just nested classes which aren't inner classes. (They're not like static classes in C#, for example.) They can still have instance methods, state etc - and there can be multiple instances.
java.lang.Math is not a static class.
And no, a class which never has an instance is not a singleton. The important difference is that a singleton can implement an interface (or even derive from an abstract class) whereas if you never create an instance of a class, any instance methods are pointless.
A class that is applied Singleton Pattern has one or none instance at any time on a JVM. That's why it's called single-ton. Having static or non-static members has no relationship with being singleton or non-singleton.
Static classes usually provide some helper methods. In fact i don't think its appropriate to compare Static classes with Singleton. Both are completely different.
We can create multiple instances of a static class but singleton guarantees(atleast in theory) only single instance.
It would have to have an instance with Singleton meaning to only be initialised, once.
Edit: Here's a link to the Wikipedia article
A singleton guarantees that there is only up to one instance of that class within the environment. It is different from a class with a bunch of static methods. A singleton carries state and can carry runtime values, while static methods of a class don't.
You can argue that you can have static values to do that, but the purpose of static variables is different (and sometimes abused like global variables). So a singleton operates in a different context than static methods.
A singleton also is usually associated with some resource (some connection to another server, access to some file, etc.) for which a static instance wouldn't be that ideal. Singletons also allow for lazy loading (if connecting or accessing a resource is expensive), while classes get loaded when the classloader encounters a reference to them.

static class vs singleton class

I know this topic has been discussed and killed over and over again, but I still had one doubt which I was hoping someone could help me with or guide me to a pre-existing post on SO.
In traditional C, static variables are stored in data segments and local variables are stored in the stack. Which I would assume will make static variables more expensive to store and maintain when compared to local variables. Right?
When trying to understand in terms of Java or C#, would this be dis-advantage for static classes when compared to singleton class? Since the entire class is loaded into memory before class initialization, I don't see how it can be an advantage unless we have small inline-able functions.
I love Singleton classes, and would hate to see it become an anti-pattern, I am still looking for all the advantages that come with it...and then loose to the argument of thread-safety among others.
-Ivar
Different from C, the static keyword in Java class definition merely means, This is just a normal class like any other class, but it just happens to be declared inside another class to organize the code. In other words, there is no behavioral difference whatsoever between the following 2 way of declaration*:
a)
class SomeOtherClass {
static class Me {
// If you "upgrade" me to a top-level class....
}
}
b)
class Me {
// I won't behave any different....
}
Class definitions are loaded to memory when the class is used for the first time, and this is true for both "static" and "non-static" classes. There are no difference in how memory will be used, either. In older JVMs, objects were always stored in heap. Modern JVMs do allocate objects on stack when that is possible and beneficial, but this optimization is transparent to the coder (it is not possible to influence this behavior via code), and use of the static keyword does not have any effect on this behavior.
Now, back to your original question, as we have seen we really can't compare static classes and Singleton in Java as they are completely different concept in Java (I'm also not sure how static classes would compare with Singleton, but I will focus on Java in this answer). The static keyword in Java is overloaded and has many meanings, so it can be confusing.
Is Singleton automatically an "anti-pattern"? I don't think so. Abuse of Singleton is, but the Singleton pattern itself can have many good uses. It just happens to be abused a lot. If you have legitimate reason to use the Singleton pattern, there is nothing wrong in using it.
*Note: Why write static at all, you might ask. It turns out "non-static" nested classes have their own somewhat complicated memory management implication, and its use is generally discouraged unless you have a good reason (pls refer to other questions for more info).
class SomeOtherClass {
Stuff stuff;
class Me {
void method(){
// I can access the instance variables of the outer instance
// like this:
System.out.println(SomeOtherClass.this.stuff);
// Just avoid using a non-static nested class unless you
// understand what its use is!
}
}
}
Singleton class is essentially a regular top-level class with a private constructor, to guarantee its singleness. Singleton class itself provides a way to grab its instance. Singleton classes are not very easy to test, therefore we tend to stick with the idea of Just Create Once.
static class is essentially a nested class. A nested class is essentially a outer level class which is nested in another class just for packaging convenience. A top-level class can not be declared as static, in Java at least -- you should try it yourself.
would this be dis-advantage for static
classes when compared to singleton
class?
Your this question became somewhat invalid now, according to the above explanation. Furthermore, a static class (of course nested) can also be a singleton.
Further reading:
Inner class in interface vs in class
The differences between one and the other is the memory management, if your app will have to instantiate a lot of things, that will burn the memory like a charm becoming a memory problem, performance and other things...
this could help...
http://butunclebob.com/ArticleS.UncleBob.SingletonVsJustCreateOne
http://www.objectmentor.com/resources/articles/SingletonAndMonostate.pdf
I'm afraid it is an anti-pattern:
http://thetechcandy.wordpress.com/2009/12/02/singletons-is-anti-pattern/

Singleton classes

Is there any difference between a Singleton class and a class with
all static members (i.e. methods and attributes).
I could not find any instance where 'all static member class' would not achieve
the same functionality as class properly implementing Singleton pattern?
For eg. java.lang.Runtime is a proper Singleton class whereas java.lang.System has all static method for access and merely has a private constructor to avoid external construction . Does anybody know why classes like Runtime are made Singleton and not implemented like java.lang.System.
Is it merely because it would be a cleaner design (i.e. mimics an object more realistically) or is there some performance benefit here?
Yes, there's a difference - a singleton can implement an interface.
Also, what looks like a singleton from the outside can actually be implemented via different classes, where the singleton access method (e.g. Runtime.getRuntime()) can create the right instance at execution time. I'm not saying that's what's happened here, but it's an option.
Well you can serialize and unserialize an object (and thus a Singleton) using the Serializable interface (on Java), but not a static class.
A singleton is instantiated once.
A static class is never instantiated.
I believe there is no difference between what you call a singleton and a class with all static methods/members in principle. In fact, I think that creating a class with all static members is a way of implementing the singleton idiom. Well, maybe in Java there is some kind of serious difference, but I'm speaking from the C++ point of view.
I think you should ask what's different between final class with private constructor and static class.
Because singleton is a class and implementation depends on programmer who programs this class.
It's same as ask what's differences between an object and static class.
A class can be extended to create another singleton (e.g. for testing purposes), or non-singleton class. static methods cannot be overidden, they can only be hidden in a sub class.
A common use for singletons with lazy initialization (aka Meyers singletons) is to control the order of static objects initialization (which, in C++, is undefined across different translation units). In this respect, singletons just behave like global objects, but whose order of construction behaves well.
It becomes quite difficult to control the order of destruction though. If you must rely on the singletons being destructed in some particular order (eg. a singleton logging class which should outlast other singleton instances), see Alexandrescu's book to witness the difficulty.
The primary purpose for singletons cited by the GoF is to provide a polymorphic service, where the singleton is an abstract base class, and the concrete type is decided at runtime. And, of course, there must only be one of them in the program.

What relevant differences are there between anonymous and predefined classes in Java?

I have a large tree-like data structure of objects which behave mostly identical but differ in one or two methods that calculate some keys used to navigate through the structure. The divergent behaviour depends on where the objects are in the structure.
I was starting out with an abstract base class and have several subclasses that implement each type of behaviour. This gives me around ten subtypes which are a) hard to name intelligently and b) look a little unwieldy in my project's source folder, both because they are so similar.
I would prefer having a single factory class that doles out instances of anonymous subclasses on the fly. This would give me a lot of flexibility and open the door for a lot of nice improvements, such as sharing data and parametrizing stuff and would look a lot cleaner in my code structure. However, the whole thing is very sensitive to memory footprint and memory access time, and I'd have lots of these objects. Do I have to consider any disadvantages or pecularities of anonymous classes?
Like non-static inner classes, anonymous classes have a hidden reference to the class they're defined in, which can cause problems if you use serialization and of course prevent objects of the outer class from being eligible for GC - but that's unlikely to be a problem if you do it in a single factory class.
Anonymous classes are not different than named classes.
But yes, having many objects can impact your memory footprint, and performance (garbage-collection).
From what you tell, I wonder if it would be possible to split your class in two parts:
All the constant methods in one class (no subclass of this class).
All variable methods (see later) are encapsulated in a Position interface. You can have a few classes that implement it. The objects of these classes would have no state, so they can be shared instances which is excellent for performance and memory).
Variable methods : calculate some keys depending on the position in the structure.
As mentioned an anonymous inner class usually has a hidden reference to the class in which it is declared. However, you can eliminate this by declaring the anonymous class from inside a static method (simple, and not perfectly obvious).
The major disadvantage to this technique is that the classnames seen in jars will be numbered (like "MyClass$0.class") and not easily identifiable in stacktraces (except of course by using the line numbers) and without toString() methods not easily identifiable in your own println statements.
Declaring static inner classes is a great technique. It will eliminate all these disadvantages and keep your file hierarchy compact. Also consider making these inner classes private or final unless you need to extend them.
A class is a class. It doesn't matter whether it's a "top-level" classes, a regular inner class, a local inner class, or an anonymous inner class.
Non-static inner classes, or inner classes that access private members of their enclosing class will have a tiny bit of extra code in them. To non-static inner classes, the compiler adds a member variable that references the enclosing instance. If an inner class accesses any private members of the enclosing class, the compiler will synthesize an accessor in the enclosing class with "package-private" (default) accessibility.

Categories