So I just started my fist big project in Java and I'm following some tutorial but there is code that I dont understand at all.
package com.Legolando.Runa;
import net.minecraftforge.fml.common.Mod;
#Mod(modid = Reference.MODID, name = Reference.MODNAME, version = Reference.VERSION)
public class Runa {
#Mod.Instance
public static Runa instance = new Runa();
// I dont get why instance of my class has to be static
}
As you see I create an instance of this class inside this class (already cosmos for me) and this instance is static. Can someone explain what is a static instance? Is it the same as static variable or method?
This code reminds me of Singleton Class in java.
public class Runa {
private static Runa singleton = new Runa( );
/* A private Constructor prevents any other
* class from instantiating.
*/
private Runa() { }
/* Static 'instance' method */
public static Runa getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
protected static void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
FYI, Singleton ensures that only one object of created for class Runa inside the application. Try to google a bit for more understanding of Singleton usage in java
Links:
https://www.tutorialspoint.com/java/java_using_singleton.htm
Best of Luck
This most probably refers to a design pattern in software development, called a singleton.
I.e. the class is designed to feature only a single instance, accessible through static means. This isn't a good example of a singleton however, as every field should only be accesses through methods. Furthermore, a private constructor might be required to prevent other classes from instantiating the singleton.
Related
I am designing a game in libgdx, and i decided to make certain manager classes singletons because I noticed that I was often only using one instance of a class, and then passing the same instance to many other classes through constructors, which was very painful to do. Now, I have one manager class that initializes many other classes in it's constructor. I did this by using static block initializers for each class, like so:
public class Example{
private static Example instance;
static{
try{
synchronized(Example.class){
instance = new Example();
}
}catch(Exception e){
throw new RunTimeException("Failure to initialize Example instance");
}
public static Example getInstance(){
return instance;
}
In the main manager I create an instance of each class through the getInstance method.
The problem that arises is this: say I have static singleton classes Example1 and Example2.
In Example1's constructor I make a variable called:
example2 = Example2.getInstance();
but because example2 and example1 need to use each other's methods, in Example2's constructor I make:
example1 = Example1.getInstance();
The problem should be easy to see. Because example1 is waiting for example2 to finish initializing, and example2 needs example1's instance, it ends up creating a deadlock and crashing through the above codes RunTimeException.
this seems easy to fix using just two example classes, but the problem is confounded when I have 6 different singleton manager classes that almost all need to communicate in some way. Easiest solution would obviously not use this methodology, but that would require me to rewrite most of my code.
I can't figure out how to use this methodology of singleton classes without running into this issue, as most of the classes need information from the other classes in the constructor in order to function.
do I remove all of the code from the constructors of the singleton classes, or do something else?
It's not a deadlock, it's infinite recursion. There is no way around it, you must refactor your code.
Best thing is not to have any logic in your constructors, just initialization of member variables. Since you don't need to store the singletons as members in your classes, there really should be no need to access them in your constructors. Just use the appropriate getInstance() method to access a singleton from inside the methods of your other singletons.
I don't use many singletons any more. I consider a singleton to be a use case, rather than a "type of class", and then rely on something else to manage the "singleton-ness" of it (such as an injection framework). When I don't have one of those, I create a single "singleton" to manage the applications classes-to-be-used-as-singletons.
So, in this case, you can have this class manage the construction and interdependencies for you rather than have the classes manage them for themselves.
public class Singletons {
private Example1 example1;
private Example2 example2;
private Example3 example3;
private static Singletons instance;
static {
Example1 example1 = new Example1();
Example2 example2 = new Example2();
Example3 example3 = new Example3();
instance = new Singletons();
example1 = new Example1();
example2 = new Example2();
example3 = new Example3();
example1.setExample2(example2);
example2.setExample3(example3);
example3.setExample1(example1);
instance.setExample1(example1);
instance.setExample2(example2);
instance.setExample3(example3);
}
public Example1 getExample1() {
return example1;
}
private void setExample1(Example1 example1) {
this.example1 = example1;
}
public Example2 getExample2() {
return example2;
}
private void setExample2(Example2 example2) {
this.example2 = example2;
}
public Example3 getExample3() {
return example3;
}
private void setExample3(Example3 example3) {
this.example3 = example3;
}
public Singletons getInstance() {
return instance;
}
}
I want to store an object state between activities (already considered Parcelables, JSON, yadda yadda) but since I have a couple of Singletons, might as well refer to them in a class that extend Application (modularity + easy to maintain).
So to my question, let's say I have a simple singleton:
class SimpleSingleton
{
private static final SimpleSingleton instance; //The question will refer this line later.
public static SimpleSingleton getInstance()
{
return instance;
}
private SimpleSingleton(){}
}
1: At first I create an initInstance() method within the above class, e.g:
class SimpleSingleton
{
//... the code above
public static void initInstance()
{
if(instance == null) instance = new SimpleSingleton();
}
}
2: Hence the below works, (in which afterwards, I can refer to the singleton from any activity via CustomSingleton.getInstance()):
class MyApp extends Application
{
#Override
public void onCreate()
{
super.onCreate();
initSingletons();
}
protected void initSingletons()
{
SimpleSingleton.initInstance();
}
}
BUT. What if I declare
private static final SimpleSingleton instance = new SimpleSingleton();
instead of
private static final SimpleSingleton instance;
in the SimpleSingleton class?
I assume the object is initialized during compile time, so doesn't that makes the whole #1 and #2 unnecessary? Or do I get the order wrong (especially WHEN the class is actually initialized)? I came from C# and currently developing for Android so this kinda gave me a quick gotcha when I want to refer to my Singletons. Also, I ask this since according to this blog:
The explanation of the weird behavior I saw that makes more sense to me is that the static variables instances are bound to the class loader of the class that first initialized them.
The only difference i can think of is when you do
private static final CustomObject instance = new CustomObject();
when you application is launched it will create and allocate space for it.
Note it might never be used but it would still be using memory.
when you create it on an onCreate method it will only create an instance when it is called.
Using static also has one more disadvantage that is it will use your perm gen space and if by chance it fails to give it space or fails to create it your program will crash on startup. Leaving you confused.
I strongly suggest using the onCreate method approach.
I have come across another article in stackexchange on various ways to implement java singleton. One of the ways shown is the following example. It has been voted very low. Wanted to understand why.
What is an efficient way to implement a singleton pattern in Java?
public class Singleton {
private static Singleton instance = null;
static {
instance = new Singleton();
// do some of your instantiation stuff here
}
private Singleton() {
if(instance!=null) {
throw new ErrorYouWant("Singleton double-instantiation, should never happen!");
}
}
public static getSingleton() {
return instance;
}
}
As #Craig says in the comments:
Not true. static variables are initialized along with static blocks when the class is loaded. No need to split the declaration.
Essentially it was down voted because it was misinformation, a lot of what he was saying was just plain not true. Specifically, initializing a static variable with a static method will occur when the class is loaded, while the author claimed that this was not the case.
His argument also doesn't really make sense, "data insertion" could just be done within the constructor.
With that said, the above code will work fine, it's just an odd way of doing it, and arguably the least stylistic.
following solution make sure it's thread safe
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() { }
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
This is not a good way to implement it.
As static variables are initialized at JVM load time, just make the singleton final:
public final class Singleton
{
private static final Singleton INSTANCE = new Singleton();
private Singleton()
{
// build it
}
public static Singleton getInstance()
{
return INSTANCE;
}
}
I know Java basics, and now I'm in the journey of reading Effective Java. The book suggest using static factory methods instead of constructors. So I have Groovy code like this:
public class Anto {
public static void main(String[] args) {
println Java.javaInstance()
}
}
class Java {
public static Java javaInstance() {
return this
}
}
When I compile this, I get an error like this:
Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'class Java' with class 'java.lang.Class' to class 'Java'
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'class Java' with class 'java.lang.Class' to class 'Java'
at Java.javaInstance(Anto.groovy:9)
at Java$javaInstance.call(Unknown Source)
at Anto.main(Anto.groovy:3)
Where am I making a mistake?
You can do it using return new Java();. Static methods don't have access to this.
EDIT:
These static factories are usually singletons, which means that only one instance of the class should be used (typically, a connection to a db for example). If you want do add this dimension to your Java class, use a private static attribute as follow:
class Java {
private static Java instance;
public static Java javaInstance() {
if(instance == null) {
instance = new Java();
}
return instance;
}
}
Creating a Singleton correctly can be easy to get wrong (especially in a multi-threaded environment), so you're probably better using the Singleton annotation that comes with Groovy rather than rolling your own:
public class Anto {
public static void main(String[] args) {
println Java.instance
}
}
#Singleton
class Java {
}
This transforms the Java class to:
class Java {
private static volatile Java instance
private Java() {}
static Java getInstance () {
if( instance ) {
instance
} else {
synchronized( Java ) {
if( instance ) {
instance
} else {
instance = new Java()
}
}
}
}
}
A good (albeit not specific to Groovy) example of a library that uses static factory methods that you could look at would be Google Guava. Guava uses this idiom in a number of places. For example, their Range class supports nine types of ranges, and if they used normal constructors, their signatures would conflict in several cases since the only thing you can use to distinguish them is their arguments.
Static methods on the other hand can also be distinguished by their name, so Guava defines different ones for each type of Range. Internally these methods still call a normal constructor, but it's not one that's publicly accessible.
import com.google.common.collect.Ranges
import com.google.common.collect.DiscreteDomains
final dom = DiscreteDomains.integers()
assert [1,2,3,4,5] as Set == Ranges.closed(1, 5).asSet(dom)
assert [2,3,4] as Set == Ranges.open(1, 5).asSet(dom)
This is a useful idiom, but not one that should just be automatically preferred over a normal constructor. In situations where a normal constructor would have sufficed, you've at best written more code than you needed and at worst have made extending the class impossible, since any subclasses will still need a public or protected constructor they can call.
You can't use this because static methods are not instance methods.
Each time you create a new instance of a particular class, that new object/instance as it's own state. this points to a particular instance.
Are you trying to make a singleton ? Meaning you just want a single instance of a class ?
class Singleton {
//static reference to a particular instance
private static Singleton instance;
//private constructor so that it cant be called outside this class scope
private Singleton();
//synchronized in case your working in threaded enviroment
public synchronized static Singleton getInstance()
{
if(NULL == instance)
{
instance = new Singleton();
}
return instance;
}
}
I'm trying to initialize a static class, with an argument, and then run some more static code in that class.
I'm aware of the static block, but it seems it can't take any arguments.
Is there a way to pass arguments to a static constructor?
If not, what is the recommended technique to initialize a Static class using an argument?
Edit:
A static class to my understanding is a class which cannot be instantiated (in c# they're called static classes, if Java has a different term for them, sorry for not being aware of it) - it's accessed through it's class name rather than an object name.
What I'm trying to achieve (very simplified) is a class which receives a dictionary as String, parses it, and has methods manipulate it like GetRandomEntry.
Here's an elaborated snippet of my code:
public class QuestionsRepository {
private static Map<String,String[]> easyDefinitions = new HashMap<String,String[]>();
//...
staticĀ
{
// need to receive and parse dictionary here
}
//...
Taking the relevant parts of a code snippet is never easy, hope i have chosen wisely (:
Another detail that may be relevant - I'm a c# programmer, usually. Just Started learning Java lately.
Thanks.
I think you would need to initialize the static fields of the class according to some input. You can do it in the following way by calling the static method of another class:
class ClassToInitialize {
static {
staticField = ParamPassClass.getParameter();
}
private static String staticField;
ClassToInitialize() {
System.out.println("This is the parameter: " + staticField);
}
}
class ParamPassClass {
private static String parameter;
static String getParameter() {
return parameter;
}
static void setParameter(String parameter) {
ParamPassClass.parameter = parameter;
}
}
class Main {
public static void main(String args[]) {
ParamPassClass.setParameter("Test param");
new ClassToInitialize();
}
}
Java doesn't have static constructors. It only has static initializers and static initializers do not take any arguments. It is executed when the class is first loaded, and there is no way to call it yourself.
You either need to use actual objects, or add some way of configuring the class (eg through a static method).
you should mention the member class with a static qualifier, otherwise there is no such a thing as a static class
Here you can find the explanation of using the word 'static' in this context.
Now you should just call its constructor and pass all the arguments you want,
the only restriction that you have on a static member class is that it can't refer the non-static fields of its outer class, it resembles a static methods on class that can't refer the non-static fields of class.
I didn't understand why do you mention a static initialization block here, could you please clarify a little?
Be aware also that in java there is no such a thing as static constructor....
Hope this helps
You can have a static method public static void setUp(Arg1 arg1, Arg2 arg2...) which sets up all your static fields and invoke it when your program starts.
You have to make sure this method will be called only once [or only when you want to reset these fields]
It is not possible to pass arguments directly to the static initializes (JLS:static initializers).
It would be nice if you could share more information about your goals.
You could use an enum to initialize a singleton with a string parameter like this
import java.util.*;
class Data {
static Map<String,String[]> easyDefinitions = new HashMap<String,String[]>();
}
public enum QuestionsRepository
{
repository("primary=red,green,blue;secondary=cyan,yellow,magenta");
QuestionsRepository(String dictionary) {
String[] rules = dictionary.split(";");
for (String rule:rules) {
String[] keyValuePair = rule.split("=",2);
Data.easyDefinitions.put(keyValuePair[0],keyValuePair[1].split(","));
}
}
}