Scope of static class variables

C

Christoph

One of my classes contains static variables that are set by the
program.

If the program is executed several times (distinct execute commands,
but the same VM and the same code base), will the two program threads
share the same static variables?

Rough example:

public class Main
{
static BufferedReader input;
static PrintStream output;

public static void main(String[] args)
{
input = new BufferedReader(new FileReader(args[0]));
...
}
}

Will this cause conflicts if the program is run on different input
files simultaneously? If so, I'd put these streams in an additional
wrapper object, but I'd rather avoid that if it's not necessary.
 
T

Tom Hawtin

Christoph said:
One of my classes contains static variables that are set by the
program.

If the program is executed several times (distinct execute commands,
but the same VM and the same code base), will the two program threads
share the same static variables?

Processes do not share statics.

However, static variables are really evil and should be avoided.

Tom Hawtin
 
C

Christoph

Processes do not share statics.

However, static variables are really evil and should be avoided.

Tom Hawtin

Not to question good programming style, but are there any cases were
non-final static variables are "okay" to use (for example in this
case, where they remain the same as long as the program runs, but
aren't hard-coded)? Or should I just get used to variables being
declared as either constants or object variables, no exceptions?
 
T

Tom Hawtin

Christoph said:
Not to question good programming style, but are there any cases were
non-final static variables are "okay" to use (for example in this
case, where they remain the same as long as the program runs, but
aren't hard-coded)?

It's very rare. There are some examples where you have a private static
final, to an object that is mutated.

For instance, you might want to associate data with objects of some type
that you cannot alter (or otherwise do not want to give it direct access
to your data). In that case you might want a concurrent, weak, identity
map (for which there is still no out of the box solution in the Java
library), mapping to your data from instances of the type you don't want
to alter.

A related concept is caching.
Or should I just get used to variables being
declared as either constants or object variables, no exceptions?

Or local variables, yes.

Tom Hawtin
 
R

Robert Klemme

It's very rare. There are some examples where you have a private static
final, to an object that is mutated.

For instance, you might want to associate data with objects of some type
that you cannot alter (or otherwise do not want to give it direct access
to your data). In that case you might want a concurrent, weak, identity
map (for which there is still no out of the box solution in the Java
library), mapping to your data from instances of the type you don't want
to alter.

A related concept is caching.

I used that once for caching bean introspection information using a
WeakHash map.

Another one is singleton pattern.

Kind regards

robert
 
T

Tom Hawtin

Robert said:
I used that once for caching bean introspection information using a
WeakHash map.

You have to be very careful there that the values do not indirectly
reference the keys. If they do, then you might as well have a HashMap
because you are going to leak.
Another one is singleton pattern.

Otherwise knows as the singleton antipattern.

Tom Hawtin
 
R

Red Orchid

I have read your articles in this thread.

Tom Hawtin said:
However, static variables are really evil and should be avoided.

Tom Hawtin said:
It's very rare. There are some examples where you have a private static
final, to an object that is mutated.


First)
The common example of "final static" variable is the instance of
a thread-safe class. For example,

<example>
class XYZ {
private static final Pattern pat = Pattern.compile("....");

boolean findXX(String s) {
Matcher m = pat.matcher(s);
....
}
}
</example>

"Pattern" is thread-safe and only one "pat" is enough/good for all
the instances of "XYZ".

What is your comment?


Next)
I think that it is not rare that static variables are not evil.
For example, (These are common cases.)

Case 1) : Thread-Safe
Write a class that returns the unique string for the entire scope of App.
(Maybe, "Message-ID" is the typical example that uses this class).

Case 2) : Thread-Safe
Write a class that calculates the network traffic for the entire scope of App.


I think that static variables should be used. That is,

<Imp of Case 1>
final class UniqueString {
private static long _val = ...;

private UniqueString() {
// no-op
}
public synchronized static String nextVal() {
return "....." + (_val++);
}
}
</Imp of Case 1>

If _val is not "static", it is possible that unique string is not guaranteed.
Because multiple instances of "UniqueString" is not prohibited.
Singleton is not proper for this case because "static" is simple.


<Imp of Case 2>
// Analogous to Implementation of Requirement 1
</Imp of Case 2>

How do you implement the above cases ?
 
T

Tom Hawtin

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
"Pattern" is thread-safe and only one "pat" is enough/good for all
the instances of "XYZ".

What is your comment?

Christ, demanding comments?

It's not mutated. I was lumping it together with other constants. Even a
Map (even ignoring Collections.unmodifiableMap) can be treated as a
constant if it is constant.
I think that it is not rare that static variables are not evil.
For example, (These are common cases.)

Case 1) : Thread-Safe
Write a class that returns the unique string for the entire scope of App.
(Maybe, "Message-ID" is the typical example that uses this class).

Case 2) : Thread-Safe
Write a class that calculates the network traffic for the entire scope of App.

You have a little class that defines the scope of the 'App'. The little
class assumes that it will never be used in a situation where the App is
duplicated across JVMs and never where to instances are used in the same
class loader context. There is no need for such a dependency. So, *if
you reasonably can avoid it*, avoid it.
final class UniqueString {
private static long _val = ...;
public synchronized static String nextVal() {
return "....." + (_val++);
}

(AtomicLong works better.)

Suppose 'unique string' is a common requirement. Shouldn't an app have
scope to have two versions of it? What if they needed to have
configurable formatting?
If _val is not "static", it is possible that unique string is not guaranteed.
Because multiple instances of "UniqueString" is not prohibited.

As I say multiple instances of UniqueString can occur, and it prohibits
reasonable use of the class.

If you want to be guaranteed of doing something once, do it once. There
is no need for statics to be involved.
Singleton is not proper for this case because "static" is simple.

A singleton is just a simple rearrangement of a static.

Tom Hawtin
 
T

Tom Hawtin

visionset said:
But easier to make it stop being

I strongly disagree with that assertion.

A singleton just adds extra syntax to the use of statics. If you want to
change something, it's easier to make start if there is less rubbish
in the way.

Tom Hawtin
 
V

visionset

Tom Hawtin said:
I strongly disagree with that assertion.

A singleton just adds extra syntax to the use of statics. If you want to
change something, it's easier to make start if there is less rubbish in
the way.

If you've got a large class you only need to remove a few lines of singleton
code and you've got an 'ordinary' class. ...Along with all the instance
attributes and inheritance hierachy - that's why you chose the singlton
route isn't it? Versus a stack of statics that need complete refactoring in
to something OO. Of course if all your singleton is, is "a simple
rearrangement of a static" then you are correct.
 
T

Tom Hawtin

visionset said:
If you've got a large class you only need to remove a few lines of singleton
code and you've got an 'ordinary' class.

And if you are using statics variables without the singleton rubbish,
you just remove the static keywords and constructor.

But that isn't the problem. The problem is that the rest of your code is
broken. You need to rewrite the code that expected the static. And that
forces you to change code that depends upon the rewritten code. And...
...Along with all the instance
attributes and inheritance hierachy - that's why you chose the singlton
route isn't it?

I don't follow.
Versus a stack of statics that need complete refactoring in
to something OO.

There is sod all OO about singletons. It's just a mechanism for people
to feel good about their botches.
Of course if all your singleton is, is "a simple
rearrangement of a static" then you are correct.

That's all singletons are.

Tom Hawtin
 
V

visionset

Tom Hawtin said:
And if you are using statics variables without the singleton rubbish, you
just remove the static keywords and constructor.

But that isn't the problem. The problem is that the rest of your code is
broken. You need to rewrite the code that expected the static. And that
forces you to change code that depends upon the rewritten code. And...


I don't follow.


There is sod all OO about singletons. It's just a mechanism for people to
feel good about their botches.


That's all singletons are.

As I ahve tried to elude to, the benefits of singletons are that they can be
seamlessly apart of a good OO design. They can partake in inheritence,
polymorphism etc and yet the decisions regarding the creational aspects and
control inversion can be delayed.
True, if all you want is a static library then there is every reason to do
just that, but a Singleton is much more, though I'd wholeheartedly agree
that is is usually misused.
 
L

Lew

visionset said:
As I ahve tried to elude [sic] to, the benefits of singletons are that they can be
seamlessly apart of a good OO design. They can partake in inheritence,
polymorphism etc and yet the decisions regarding the creational aspects and
control inversion can be delayed.

If you have polymorphism in a singleton, that implies more than one object
could fill the singleton position. Is that really a singleton?
True, if all you want is a static library then there is every reason to do
just that, but a Singleton is much more, though I'd wholeheartedly agree
that is is usually misused.

By being used.
 
C

Chris Uppal

Lew said:
If you have polymorphism in a singleton, that implies more than one object
could fill the singleton position. Is that really a singleton?

Sure, even assuming that you want to enforce uniqueness on your singleton, it
can still be polymorphic with other objects. As in:

interface DrawingSurface
{
void drawLine();
void drawText();
... etc ...
}

public class PrintingSuface
implements DrawingSurface
{
public static // ctor
PrintingSuface(Sting printerName)
{
....
}

... etc ...
}

public final class DesktopDisplaySurface
implements DrawingSurface
{
public static DesktopDisplaySurface
theOnlyInstance()
{
...
}

private // ctor
DesktopDisplaySurface()
{
...
}

... etc ...
}

Uniqueness (whether enforced by the application architecure or not) is not at
all incompatible with polymorphism.

-- chris
 
T

Tom Hawtin

Chris said:
Sure, even assuming that you want to enforce uniqueness on your singleton, it
can still be polymorphic with other objects. As in:

Which isn't an advantage singletons have over plain old statics. The
static version just has a tighter interface.

Tom Hawtin
 
C

Chris Uppal

Tom said:
Which isn't an advantage singletons have over plain old statics. The
static version just has a tighter interface.

??

I don't understand your point here. Polymorphism isn't an advantage or a
disadvantage, its a design option. If two objects can be used polymorphically
with each other (in certain contexts) then there's no /advantage/ there over
objects which cannot be used polymorphically -- the latter two objects just
form part of a different design (which may in itself be better or worse).

If you need a one or more objects which fulfil a certain polymorphic role then
it doesn't matter whether:
1) there are several such object in the system;
2) there happens only to be one such object in the system;
3a) there is one such object in the system which is specially important;
3b) it only makes sense to have one such object in the system;
4) there /must/ only be one such object in the system;
(where (1) or (2) are the typical cases. (3a) and (3b) are the cases addressed
by
Singleton when properly used. (4) is a case which occurs so rarely that
there's little real point in giving it a Pattern Name, but it can be seen as a
special case of Singleton.)

In any such case, statics just don't enter the frame. They have no relevance
to such a design at all, except perhaps to help with the /implementation/ of
(3) or (4) (always subject to the condition that the "system"s scope is no
wider than the class's -- often, but not always, true).

If polymorphism isn't a requirement, then the same data (and even behaviour)
could be encoded as class-side stuff (subject to the same condition on what
"system" means).

-- chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,990
Messages
2,570,211
Members
46,796
Latest member
SteveBreed

Latest Threads

Top