Java static variable updates - java

Below you can see a static variable counter in a Java class.
The question is when will this variable reset? For example, when I restart the program, computer. What are the other possible scenarios it can reset?
Another question is: what could be the reasons for this variable to increase by less than the number of times the function do() is executed? For example, could it be something with starting multiple processes of the class java Whatever? Or could it be something with multiple threads/servers, etc?
class Whatever {
static int counter = 0;
function do() {
counter++;
//...
}
}
Additional question: If multiple threads execute function do(), how will the counter variable behave? It will be less than the number of times function do() was executed?

A static variable will be re-initialized when you restart the application.

According to the JLS:
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
So this answers your first question. i.e.e exactly when the class is loaded :)
As per second question, nope. if the variable is declared private. Then the only access is via the method because of encapsulation.
Static variables lasts till the JVM is shutdown.

counter is not a private variable. So it is possible that this value is changed by some other class.
This variable will get reset whenever your program (or specifically the container/jvm) is restated.

1) The variable is set(reset) when the class is loaded. Apart from shutting down the JVM, some servers load the class in different applications (v.g., the Tomcat webapps) and some of them allow restarting them.
2) Concurrent modification by threads. But it should be rare, unless you use it a lot. Use synchronized for the function/block.

The question is when will this variable reset?
static variable can be reset using custom reset() method. If You say restart program, theoretically that variable will be initialized to it's value not reinitialized as it is not same(you restart program).

class Foo { // in same package
public static void main(String[] args) {
Whatever w = new Whatever();
for (int i = 0; i < 1000; i++) {
w.do();
}
Whatever.counter = -1;
}
here do() is invoked 1000 times, but counter will have value at the end.
I used do() like you in your example, but note that is not a valid method name, because it's the keyword for a do while loop.

A static variable means that there are only one incarnation of that field during a program execution. It is loaded when the class is initialized.
For your second question, your variable isn't thread safe because multiple threads can access it at the same time.
Even if your counter was volatile you would still face concurrency problem.
You have three options, given your example and requirements:
If your only requirement is to manipulate the variable and the rest of the code won't depend of that you can use synchronize (killing a fly with a cannon) or AtomicInteger (the choice with better performance):
static synchronize int counter = 0;
// or
static AtomicInteger counter = new AtomicInteger();
If the rest of your code is dependent of your counter, you must use a lock object or synchronize your method:
class Whatever {
static int counter = 0;
synchronize function do() {
counter++;
if(counter < 10){
// do something
}
}
}
// or
class Whatever {
static int counter = 0;
static final Object _lock = new Object();
function do() {
synchronized (_lock) {
counter++;
if(counter < 10){
// do something
}
}
}
}
This are the options that are in my head right now, but probably there are more.

Related

Process flow of a Closure example | Java 8

Was going through a closure example for the first time , but I'm having a hard time wrapping my head around the control flow.
public class TestLambdaClosure {
public static void main(String[] args) {
int a= 10;
int b=20;
//doProcess(a, i-> System.out.println(i+b));
doProcess(a, new Process() {
#Override
public void process(int i) {
System.out.println(i+b);
}
});
}
public static void doProcess(int i, Process p) {
p.process(i);
}
interface Process{
void process(int i);
}
}
How does 'b' get in the scope when p.process(i) is called? Also, how does the control flow work here internally?
Closures allow you to model behavior by encapsulating both code and context into a single construct.
The key concept is that your function code (lambda) can refer to not only its own variables, but also to everything outside visible for the code, variables a and b in your case.
In Java, closures can refer only to final or effectively final variables. It means, the reference of the variable cannot change and the closure sees only the actual immutable state (the value is actually not immutable, final means the variable cannot be reassigned). In the theory, this is not necessary. For example in JavaScript, you can write such code:
function newCounter() {
    let count = 0;
    return function() { return ++count; };
}
const nc = newCounter();
console.log(nc()); // 1
console.log(nc()); // 2
console.log(nc()); // 3
Here, the inner function of newCounter still has access to count (its context) and can modify it (the variable is mutable).
Notice, that variable counter is not accessible to any other parts of your code outside of the closure.
Closures let you access variables in their outer scopes. Outer scope variable in this case (b) is declared as what java community now it calls effectively final, meaning that it's value isn't changed since initialization ( int b = 20 ) in order to be accessible.
Bare in mind that variables need to be declared as final or effectively final in order for this to work as closures.
Now regarding your code, this code declares doProcess(...) method that returns a method for partial performing of the doProcess(...) method.
The process(...) method accesses b in the outer scope of the doProcess(...) method, which is declared as effectively final.

How can i call a variable from another method

I need to know how to call a variable from one method to another
Can anyone help me?
public static void number(){
number = 1;
}
public static void callNumber(){
/*How can I call number to this method???
*/
}
Actually, "call a variable from an other method" is not very explicit, since a variable in a method is either global (used in the method but naturally available in the entire program), or a local variable of the method.
And in this last situation it is impossible to get this value.
Then either you declare your variable externally and it is trivial, or you specifiy a type value to your method "number()":
public static int number() {
int number = ...;
return number;
}
and you call it:
public static void callNumber() {
int numberReturned = number();
// other things...
}
Note: your code number = 1; specifies that your variable is global...
The trick is to set "number" available either by the return of the method, or by specifying this variable global.
I don't know if I've answered your question, if not try to be more explicit.
Between static methods, variables can be shared by making them global,
or by sending them as parameters(noas described by #Gaétan Séchaud).
However, if those two methods has a continuos connection between them, and they handle some variables needed to be shared, it smells like a class is needed.

Does Java support static variables inside a function to keep values between invocations?

https://stackoverflow.com/a/572550/1165790
I want to use this feature in Java because the function that I'm designing is called rarely (but when it is called, it starts a recursive chain) and, therefore, I do not want to make the variable an instance field to waste memory each time the class is instantiated.
I also do not want to create an additional parameter, as I do not want to burden external calls to the function with implementation details.
I tried the static keyword, but Java says it's an illegal modifier. Is there a direct alternative? If not, what workaround is recommended?
I want it to have function scope, not class scope.
I want it to have function scope, not class scope.
Then you are out of luck. Java provides static (class scoped), instance and local variables. There is no Java equivalent to C's function-scoped static variables.
If the variable really needs to be static, then your only choice is to make it class scoped. That's all you've got.
On the other hand, if this is a working variable used in some recursive method call, then making it static is going to mean that your algorithm is not reentrant. For instance, if you try to run it on multiple threads it will fall apart because the threads will all try to use the same static ... and interfere with each other. In my opinion, the correct solution would be either to pass this state using a method parameter. (You could also use a so-called "thread local" variable, but they have some significant down-sides ... if you are worrying about overheads that are of the order of 200 bytes of storage!)
How are you going to keep a value between calls without "wasting memory"? And the memory consumed would be negligible.
If you need to store state, store state: Just use a static field.
Caution is advised when using static variables in multi-threaded applications: Make sure that you synchronise access to the static field, to cater for the method being called simultaneously from different threads. The simplest way is to add the synchronized keyword to a static method and have that method as the only code that uses the field. Given the method would be called infrequently, this approach would be perfectly acceptable.
Static variables are class level variables. If you define it outside of the method, it will behave exactly as you want it to.
See the documentation:
Understanding instance and Class Members
The code from that answer in Java...
public class MyClass {
static int sa = 10;
public static void foo() {
int a = 10;
a += 5;
sa += 5;
System.out.println("a = " + a + " sa = " + sa);
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
foo();
}
}
}
Output:
$ java MyClass
a = 15 sa = 15
a = 15 sa = 20
a = 15 sa = 25
a = 15 sa = 30
a = 15 sa = 35
a = 15 sa = 40
a = 15 sa = 45
a = 15 sa = 50
a = 15 sa = 55
a = 15 sa = 60
sa Only exists once in memory, all the instances of the class have access to it.
Probably you got your problem solved, but here is a little more details on static in Java. There can be static class, function or variable.
class myLoader{
static int x;
void foo(){
// do stuff
}
}
versus
class myLoader{
static void foo(){
int x;
// do stuff
}
}
In the first case, it is acting as a class variable. You do not have to "waste memory" this way. You can access it through myLoader.x
However, in the second case, the method itself is static and hence this itself belongs to the class. One cannot use any non-static members within this method.
Singleton design pattern would use a static keyword for instantiating the class only once.
In case you are using multi-threaded programming, be sure to not generate a race condition if your static variable is being accessed concurrently.
I agree with Bohemian it is unlikely memory will be an issue. Also, duplicate question: How do I create a static local variable in Java?
In response to your concern about adding an additional parameter to the method and exposing implementation details, would like to add that there is a way to achieve this without exposing the additional parameter. Add a separate private function, and have the public function encapsulate the recursive signature. I've seen this several times in functional languages, but it's certainly an option in Java as well.
You can do:
public int getResult(int parameter){
return recursiveImplementation(parameter, <initialState>)
}
private int recursiveImplementation(int parameter, State state){
//implement recursive logic
}
Though that probably won't deal with your concern about memory, since I don't think the java compiler considers tail-recursive optimizations.
The variables set up on the stack in the recursive call will be function (frame) local:
public class foo {
public void visiblefunc(int a, String b) {
set up other things;
return internalFunc(a, b, other things you don't want to expose);
}
private void internalFunc(int a, String b, other things you don't want to expose) {
int x; // a different instance in each call to internalFunc()
String bar; // a different instance in each call to internalFunc()
if(condition) {
internalFunc(a, b, other things);
}
}
}
Sometimes state can be preserved by simply passing it around. If required only internally for recursions, delegate to a private method that has the additional state parameter:
public void f() { // public API is clean
fIntern(0); // delegate to private method
}
private void fIntern(int state) {
...
// here, you can preserve state between
// recursive calls by passing it as argument
fIntern(state);
...
}
How about a small function-like class?
static final class FunctionClass {
private int state1; // whichever state(s) you want.
public void call() {
// do_works...
// modify state
}
public int getState1() {
return state1;
}
}
// usage:
FunctionClass functionObject = new FunctionClass();
functionObject.call(); // call1
int state1AfterCall1 = functionObject.getState1();
functionObject.call(); // call2
int state1AfterCall2 = functionObject.getState1();

Is incrementing an integer thread safe in java?

Java Code:
public class IncreaseTest {
public static int value = 0;
public synchronized int increment() {
return value++;
}
}
Is method increment() thread-safe? Do I have to add the modifier keyword volatile as follows:
public static volatile int value = 0;
This code is not thread-safe. The instance method will synchronize on an instance, if you have multiple instances they will not use the same monitor and therefor the updates can interleave.
You either need to remove the static from the value field or add static to the increment() method.
Also, as you have made value public, there is the additional problem that value can be changed or read outside of this method without using synchronisation which could result in reading old values.
So changing your code to the following will make it thread-safe:
public class IncreaseTest {
private int value = 0;
public synchronized int increment() {
return value++;
}
}
You should probably use atomicvars
If you are using this method in two threads then you do need the volatile keyword. Without it, another thread may not get the most up to date value. (C#)
I do not think this is thread safe since the static variable is public and can be accessed by other threads in a non-thread safe manner. In order to be thread safe you must declare the variable as follows:
public static volatile int value;
Now value being volatile, will be accessed in a synchronized block.

declaration of variable inside a loop vs multiple declarations of the same variable name

the following code gives an error, because the variable m was defined twice.
class one {
public static void main(String args[]) {
int m=10;
int m=10;
}
}
but when the declaration is done inside a loop, it is OK, even though m is still being defined twice.
class one {
public static void main(String args[]) {
for(int i=1;i<=2;i++) {
int m=10;
}
}
}
and the compiler does not give back an error message.
can you explain the differences between the two, and how come sometimes i can declare the same variable twice inside the same method, and sometimes not?
For the first case m is referenced till the end of the main method so you can't have two variable of the same name in the same scope.
Whereas in the second case, for every time the loop executes, m for the last iteration is no longer referenced and hence you are able to redeclare and reinitialize it.
You cannot declare a variable with the same name more than once in a block of code.
In first case, you are declaring the same variable in a block of code i.e. main.
In second case, after the first iteration of for loop, variable m is destroyed and recreated over the second iteration
It's creating an error in the first one because you are declaring the varible twice.
you get the error is because you defined the same variable twice in the same block (scope). when you run inside a loop, you "open" a new scope for every iteration of the loop, so you can define a variable that is visible only within this scope (won't be accible outside the loop though). for instance, if you had written something like that:
class one {
public static void main(String args[]) {
{
int m=10;
}
{
int m=10;
}
}
}
it would have been compiled just fine, because the variables of the same name, does not share the same scope.
- In the First code you have declared m twice in the same scope, and it continues till the main() method ends.
- Where as within the loop everytime a primitive int variable m is created with a value, so its obviously not a problem.
In simple words, you are not declaring this variable twice in second example. As variable lifespan ends on the closing } of the block in which it was declared, by the time you declare m in second iteration, first one is "dead". This is why you can do it in a loop.
In first example you declare two variables with the same name in the same code block, which are supposed to "live" simultaneously. This is forbidden as you can't tell which variable you refer too by writing m.

Categories