Reputation: 2416
I just discovered an apparent gap in my Android/Java understanding. In particular, it appears that static class variables are preserved between different invocations of my app.
Is this to be expected?.
I did a diligent search of StackOverflow and elsewhere but I can find no mention of this. As an experiment, I tried the following code in my initial Activity:
static int MyCount;
...
public void onCreate(Bundle savedInstanceState) {
Log.d( "MYAPP", "MyCount="+MyCount );
MyCount++;
...
If I exit the app (via finish()) and restart it, MyCount keeps getting incremented. This surprised me. Is this an expected behavior?
(and please, no lectures on the evils of static variables :)
Upvotes: 2
Views: 2033
Reputation: 234875
The lifetime of a static is limited to the lifetime of the JVM associated with the particular class loader that loaded the first instance of the class.
So no, it would not be shared across separate processes.
It's worth pointing out that int
is an atomic type in Java, but long
might not be. Do bear that in mind when considering the thread safety of onCreate
.
Upvotes: 0
Reputation: 1007564
Is this to be expected?.
That depends entirely upon what you mean by "invocations of my app".
Let's suppose that you have a single-activity application. You then manually execute the following pseudo-code:
for
click on app's icon in home screen launcher
click BACK to destroy that activity and return to the home screen launcher
while not tired of doing this yet
Assuming no significant delays in loop processing, you will maintain one process for the entirety of the loop, and therefore your static data members will still exist.
The lifetime of static data members is the lifetime of the Java process, and you do not control when your process goes away.
Upvotes: 2
Reputation: 3767
No, static variables are not preserved between multiple app instances.
This is most likely because you didn't completely close your app (via settings->stop process or a similar method) but instead your app was simply running in the background and preserving the value of the static variable.
Upvotes: 2