Variable available thoughout java program (singleton) - java

I need to set a boolean variable at runtime that can be accessed by any other class (without having to pass the variable around from class to class). This variable will be a configuration setting, and will depend on some value set by the user at runtime.
I suspect a singleton is the way to go, but having spent the morning reading up on it, I seem to find a lot of examples (& arguments) on the best way to create them, without any mention of how to actually use them.
Is singleton the way to solve this?
If so, can anyone provide an example of a singleton, that can have a boolean value set, that can be accessed statically from any other class?
EDIT: I'm such an idiot (totally overcomplicating the problem, and missing the simplest solution).
public static volatile boolean yourBoolean; Looks like it'll work perfectly

If you just need a boolean value, there is no need to use a singleton. Just declare a:
public static volatile boolean yourBoolean;
(with the volatile keyword to make sure that all changes made are visible across threads if you are in a multi-threaded environment).

If the variable will contain a configuration setting that won't change during runtime, I suggest you use a final static variable. See the example below:
public class Main {
public final static String CONFIGURATION_SETTING = "some_setting";
}
You can access this constant by using the following reference:
Main.CONFIGURATION_SETTING
It will be available throughout your solution, as long as you import the Main class.

I don't think a singleton is necessarily what you need here - as your question itself states, all that you need is a variable that can be accessed by any other class.
Since you don't want to pass anything round, it must be static - and of course it will have to be public in order for other classes to see it.
So the simplest way to achieve this would be something like the following:
public class Config {
public static boolean flag;
}
Any class can then read the value as Config.flag.
If you have multiple threads in your application, you'll need to think about thread-safety. For simple, single boolean values you can just mark the field as volatile. But if you're doing something a little more complex, or updating several values at once, you'll need to ensure that these updates are atomic and visible to other threads in an appropriate fashion.

Related

When using static classes in java

I am not very familiar with java. I created a jersey web server. There is different functions such as startRodio(), stopRadio(), setRadioIp()... I created one RequestHandler class to handle the http requests and one other Radio class that implement them. All the properties and methods of the Radio class are static. it looks like
Radio
class Radio{
public static boolean radionOn;
public static String radioIpadress;
public static boolean startRadio(){
radioOn = true;
// some other operation
}
...
RequestHandler
classe RequestHandler {
#path(/startRodio)
.....
if (!Rodio.radioOn)
Radio.startRadio();
Is it a good architecture for my programm? is it a good practice to make all the properties and method static in this way?
I would say, that making properties static in default as you have made above is not good practice at all.
If you have only one instance of such object as Radio is, then use singleton pattern and private properties with proper getters and setters. This is generally best approach, because you separate public interface from private implementation and change in the implementation (e.g. renaming variable) would cause problems in other parts of application and need of refactoring.
Static variables should serve just for some common properties for defined type/class. You can for example count existing instances of class in static variable.
Better avoid using static variables. This is not a good practice. Static variables have global scopes which leaves you testing so hard. Also anything can be able to modify the static variables. more over, using static is not thread safety. Also you don't have control over the static variable i terms of their creation and destruction. SO its not advisable to use statics.
Just don't use static variables. It directly couples several of
your classes.
You can use singletons in place of static if you're sure that you
need only one object.
Simply spoken: don't use static.
static is an abnormality in good OO design. It leads to direct coupling between your classes. It makes it hard to later replace "implementation"; and it makes it hard to write reasonable unit tests.
Meaning: by default, you do not use static. There might be situations when it is fine to use; but the example code you are showing does not at all look like you should be using static.
Instead, you should be defining an interface that denotes the functionality of your Radio; allowing for different implementations behind that interfaces.
It depends on what are you looking for.
Lets say you are creating 4 objects of Radio.
radioOne....,radioFour...
Now if you want all Radios to start at same time, you should go for static variable because static properties are characteristics of all objects of a class. They are not exclusive to any particular object and in practice they should be assessed using class like :
Radio.radionOn=true;
and not radioOne.radioOn=true;
So, I would suggest you to make only those properties static which will be common to all objects. If all the properties will fall under that ambit,
then it would mean you want only one object for the class because all your objects would behave the same .So better to have one object . In that case go for singleton pattern for object creation.

Is there ever a correct time to use a public variable?

Is there a situation were using a public variable would be beneficial? If not, why do they even exist?
Also I am specifically talking about Java, but if they have use in another language perhaps that would give reason to their existence.
Yes, I use them for my representation of a vector.
public class Vec3f {
public final float x, y, z;
// the methods
}
Note that because these are final primitives it is safe to expose them. This is shorter in code and uses less method calls (none).
In general, they are viable to use in value-objects (let's use that name) if made final.
I define value-objects as possibly immutable, possibly short-lived objects holding just data, yielding new objects on mutation.
You shouldn't use public non-final variables in your public API though...
public static final variables are a common and handy way of defining constants
Public member variables are a little harder to justify, but I have seen a massive number of bean type objects with a load of private member variables and a corresponding set of getters and setters that do nothing but return or set the private variables. In those cases, there is an argument to make those variables public as the data is hardly "encapsulated" by the class - the user can set it to whatever they like, and they retrieve whatever the variable is set to without any modification.
I don't do it personally, but I'm not 100% against it either.
Global variables (when the language allows), can cause major problems especially in complex systems, where a piece of code can change its value at any time. Besides creating a coupling between places that should not have.
so avoid
In java I usually use public final constants in a single centralized source.

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

when exactly are we supposed to use "public static final String"?

I have seen much code where people write public static final String mystring = ...
and then just use a value.
Why do they have to do that? Why do they have to initialize the value as final prior to using it?
UPDATE
Ok, thanks all for all your answers, I understand the meaning of those key (public static final). What I dont understand is why people use that even if the constant will be used only in one place and only in the same class. why declaring it? why dont we just use the variable?
final indicates that the value of the variable won't change - in other words, a constant whose value can't be modified after it is declared.
Use public final static String when you want to create a String that:
belongs to the class (static: no instance necessary to use it), that
won't change (final), for instance when you want to define a String constant that will be available to all instances of the class, and to other objects using the class, and that
will be a publicly accessible part of the interface that the class shows the world.
Example:
public final static String MY_CONSTANT = "SomeValue";
// ... in some other code, possibly in another object, use the constant:
if (input.equals(MyClass.MY_CONSTANT)
Similarly:
public static final int ERROR_CODE = 127;
It isn't required to use final, but it keeps a constant from being changed inadvertently during program execution, and serves as an indicator that the variable is a constant.
Even if the constant will only be used - read - in the current class and/or in only one place, it's good practice to declare all constants as final: it's clearer, and during the lifetime of the code the constant may end up being used in more than one place.
Furthermore using final may allow the implementation to perform some optimization, e.g. by inlining an actual value where the constant is used.
Finally note that final will only make truly constant values out of primitive types, String which is immutable, or other immutable types. Applying final to an object (for instance a HashMap) will make the reference immutable, but not the state of the object: for instance data members of the object can be changed, array elements can be changed, and collections can be manipulated and changed.
Static means..You can use it without instantiate of the class or using any object.
final..It is a keyword which is used for make the string constant. You can not change the value of that string. Look at the example below:
public class StringTest {
static final String str = "Hello";
public static void main(String args[]) {
// str = "world"; // gives error
System.out.println(str); // called without the help of an object
System.out.println(StringTest.str);// called with class name
}
}
Thanks
The keyword final means that the value is constant(it cannot be changed). It is analogous to const in C.
And you can treat static as a global variable which has scope. It basically means if you change it for one object it will be changed for all just like a global variable(limited by scope).
Hope it helps.
static means that the object will only be created once, and does not have an instance object containing it. The way you have written is best used when you have something that is common for all objects of the class and will never change. It even could be used without creating an object at all.
Usually it's best to use final when you expect it to be final so that the compiler will enforce that rule and you know for sure. static ensures that you don't waste memory creating many of the same thing if it will be the same value for all objects.
final indicates that the value cannot be changed once set. static allows you to set the value, and that value will be the same for ALL instances of the class which utilize it. Also, you may access the value of a public static string w/o having an instance of a class.
 public makes it accessible across the other classes. You can use it without instantiate of the class or using any object.
 static makes it uniform value across all the class instances.
It ensures that you don't waste memory creating many of the same thing if it will be the same value for all the objects.
 final makes it non-modifiable value. It's a "constant" value which is same across all the class instances and cannot be modified.
You do not have to use final, but the final is making clear to everyone else - including the compiler - that this is a constant, and that's the good practice in it.
Why people doe that even if the constant will be used only in one place and only in the same class: Because in many cases it still makes sense. If you for example know it will be final during program run, but you intend to change the value later and recompile (easier to find), and also might use it more often later-on. It is also informing other programmers about the core values in the program flow at a prominent and combined place.
An aspect the other answers are missing out unfortunately, is that using the combination of public final needs to be done very carefully, especially if other classes or packages will use your class (which can be assumed because it is public).
Here's why:
Because it is declared as final, the compiler will inline this field during compile time into any compilation unit reading this field. So far, so good.
What people tend to forget is, because the field is also declared public, the compiler will also inline this value into any other compile unit. That means other classes using this field.
What are the consequences?
Imagine you have this:
class Foo {
public static final String VERSION = "1.0";
}
class Bar {
public static void main(String[] args) {
System.out.println("I am using version " + Foo.VERSION);
}
}
After compiling and running Bar, you'll get:
I am using version 1.0
Now, you improve Foo and change the version to "1.1".
After recompiling Foo, you run Bar and get this wrong output:
I am using version 1.0
This happens, because VERSION is declared final, so the actual value of it was already in-lined in Bar during the first compile run. As a consequence, to let the example of a public static final ... field propagate properly after actually changing what was declared final (you lied!;), you'd need to recompile every class using it.
I've seen this a couple of times and it is really hard to debug.
If by final you mean a constant that might change in later versions of your program, a better solution would be this:
class Foo {
private static String version = "1.0";
public static final String getVersion() {
return version;
}
}
The performance penalty of this is negligible, since JIT code generator will inline it at run-time.
Usually for defining constants, that you reuse at many places making it single point for change, used within single class or shared across packages. Making a variable final avoid accidental changes.
Why do people use constants in classes instead of a variable?
readability and maintainability,
having some number like 40.023 in your code doesn't say much about what the number represents, so we replace it by a word in capitals like "USER_AGE_YEARS". Later when we look at the code its clear what that number represents.
Why do we not just use a variable? Well we would if we knew the number would change, but if its some number that wont change, like 3.14159.. we make it final.
But what if its not a number like a String? In that case its mostly for maintainability, if you are using a String multiple times in your code, (and it wont be changing at runtime) it is convenient to have it as a final string at the top of the class. That way when you want to change it, there is only one place to change it rather than many.
For example if you have an error message that get printed many times in your code, having final String ERROR_MESSAGE = "Something went bad." is easier to maintain, if you want to change it from "Something went bad." to "It's too late jim he's already dead", you would only need to change that one line, rather than all the places you would use that comment.
public makes it accessible across other classes.
static makes it uniform value across all the class instances.
final makes it non-modifiable value.
So basically it's a "constant" value which is same across all the class instances and which cannot be modified.
With respect to your concern "What I don't understand is why people use that even if the constant will be used only in one place and only in the same class. Why declaring it? Why don't we just use the variable?"
I would say since it is a public field the constant value can also be used elsewhere in some other class using ClassName.value. eg: a class named Math may have PI as final static long value which can be accessed as Math.PI.
It is kind of standard/best practice.
There are already answers listing scenarios, but for your second question:
Why do they have to do that? Why do they have to initialize the value as final prior to using it?
Public constants and fields initialized at declaration should be "static final" rather than merely "final"
These are some of the reasons why it should be like this:
Making a public constant just final as opposed to static final leads to duplicating its value for every instance of the class, uselessly increasing the amount of memory required to execute the application.
Further, when a non-public, final field isn't also static, it implies that different instances can have different values. However, initializing a non-static final field in its declaration forces every instance to have the same value owing to the behavior of the final field.
This is related to the semantics of the code. By naming the value assigning it to a variable that has a meaningful name (even if it is used only at one place) you give it a meaning. When somebody is reading the code that person will know what that value means.
In general is not a good practice to use constant values across the code. Imagine a code full of string, integer, etc. values. After a time nobody will know what those constants are. Also a typo in a value can be a problem when the value is used on more than one place.
I think these are all clear explanations. But, Let me clarify it by giving a java inbuild example.
In java, most would have used System.out.println()
The system is a class and out is a PrintStream class.
So what java says is I will take care of the initialization of the out object(PrintStream) and keep the initialization private to myself in the System class.
public final class System {
public final static PrintStream out = null;
//Some initialization done by system class which cannot be changed as it is final.
}
You just access the println method statically without worrying about its initialization.

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.

Categories

Resources