Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / April 2007

Tip: Looking for answers? Try searching our database.

Scope of static class variables

Thread view: 
Christoph - 03 Apr 2007 14:57 GMT
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.
Tom Hawtin - 03 Apr 2007 15:11 GMT
> 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
Christoph - 03 Apr 2007 15:29 GMT
> > One of my classes contains static variables that are set by the
> > program.
[quoted text clipped - 8 lines]
>
> 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?
Tom Hawtin - 03 Apr 2007 15:45 GMT
> 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
Robert Klemme - 03 Apr 2007 16:16 GMT
>> Not to question good programming style, but are there any cases were
>> non-final static variables are "okay" to use (for example in this
[quoted text clipped - 12 lines]
>
> 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
Tom Hawtin - 03 Apr 2007 18:26 GMT
> 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
Red Orchid - 03 Apr 2007 18:48 GMT
I have read your articles in this thread.

Tom Hawtin <usenet@tackline.plus.com> wrote or quoted in
Message-ID <4612603d$0$8725$ed2619ec@ptn-nntp-reader02.plus.net>:

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

Tom Hawtin <usenet@tackline.plus.com> wrote or quoted in
Message-ID <46126833$0$8732$ed2619ec@ptn-nntp-reader02.plus.net>:

> > Not to question good programming style, but are there any cases were
> > non-final static variables are "okay" to use (for example in this
[quoted text clipped - 3 lines]
> 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 ?
Tom Hawtin - 03 Apr 2007 19:29 GMT
> Tom Hawtin <usenet@tackline.plus.com> wrote or quoted in

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

> "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.)
[quoted text clipped - 5 lines]
> 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
visionset - 04 Apr 2007 01:24 GMT
> A singleton is just a simple rearrangement of a static.

But easier to make it stop being

Signature

Mike W

Tom Hawtin - 04 Apr 2007 04:12 GMT
>> A singleton is just a simple rearrangement of a static.
>
> 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
visionset - 04 Apr 2007 11:15 GMT
>>> A singleton is just a simple rearrangement of a static.
>>
[quoted text clipped - 5 lines]
> 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.

Signature

Mike W

Tom Hawtin - 04 Apr 2007 11:30 GMT
> 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
visionset - 04 Apr 2007 15:52 GMT
>> 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.
[quoted text clipped - 22 lines]
>
> 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.

Signature

Mike W

Lew - 04 Apr 2007 23:38 GMT
> 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.

Signature

Lew

Chris Uppal - 05 Apr 2007 09:35 GMT
> 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
Tom Hawtin - 05 Apr 2007 10:40 GMT
>> 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:

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

Tom Hawtin
Chris Uppal - 05 Apr 2007 11:40 GMT
> > > If you have polymorphism in a singleton, that implies more than one
> > > object could fill the singleton position.  Is that really a singleton?
[quoted text clipped - 4 lines]
> 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


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.