4

What is the best way to create a C-style static variable in Java (local to a method)?

I have a method in which I need to calculate a variable only once, and do not need to recalculate it for the lifetime of the object.

I understand that I could create a final field, but this variable may not be required in all cases and would only be required if this method in question is called at all by the client.

Any pointers on how I could achieve this?

2
  • At which point of time are you able to calculate the variables value? Compile time/run time/method invocation time? Commented Aug 30, 2010 at 23:38
  • A word of warning: In C++ static variables inside a class method are static within the context of the class and not the object instance. stackoverflow.com/a/6223689/1741 Commented Feb 4, 2014 at 16:36

5 Answers 5

4

C++ static locals are equivillant to static fields with lazy initialization.

C++:

class Example {
 public:
  void method() {
    static Something something;
  }
};

Java:

public class Example {
    private static Something something;
    public void method() {
        if (something == null) something = new Something();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I would use lazy initialization wherever this thing is called. Local memoization if well thought through creates less chaos than distributing it over multiple classes.

If you need to share even then a lazy static initialization in a for the rest stateless service is better than a Singleton. If caching/memoization is local (and appropriate) it does not break the 'stateless' mental picture which helps keep code clean.

However caching/memoization is a pain to test. But mocking stateless beans is trivial, and independently verifying the cache works, is easy too.

Comments

1

local to a method
for the lifetime of the object

For me those two sentences are mutually exclusive in the java world. You either want a variable local to a method or an instance variable. Judging by what you said you want the latter. To initialize it you can use, as someone already said, the lazy loading pattern which will initialize it when, and only when, you need it. The downside would be checking in other methods whether it was initialized.

Doing things in Java the C way isn't the best idea imho.

Comments

0

Use the Lazy Load pattern.

3 Comments

He wants to know how to create the c-style static variables local to a function that he wants to use with his lazy loading. This is correct - but he wants a way to not have to create a private variable in the class that pollutes the namespace.
Then he requests the impossible ;)
One private class variable isn't much of a price to pay to do it the OOP way. The point of private variables is to avoid namespace pollution in the first place.
0

I think you may be referring to a "lazy cache" type of strategy. Like this:

class LazyCacheExample {

    Integer x = null;

    public Integer calculateX() {
        // if x has not been calculated yet, calculate it now
        if (null == this.x) {
            // TODO consider thread safety here... 
            this.x = 2+2; 
        }

        // otherwise return the calculated object
        return this.x;
    }   
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.