3

I am new to Java and started learning and exploring bit about language. Could anyone explain what is significance of _() in that constructor. Is that called constructor?

public class UserRequestCache {

    private final static ThreadLocal <UserRequest> t = new ThreadLocal <UserRequest>();

    private static UserRequestCache instance = new UserRequestCache();

    public static UserRequestCache _() {
        return instance;
    }

    private UserRequestCache() {
    }

    public void checkPoint() {
        if (logDebug()) {
            if (getUserRequest() != null) {
                logDebug(getUserRequest().toString());
            }
        }
    }

    public UserRequest getCache() {
        // checkPoint();
        return getUserRequest();
    }

    private UserRequest getUserRequest() {
        return t.get();
    }

    public void setCache(UserRequest value) {
        t.set(value);
    }
}
Nelson Lang
  • 51
  • 1
  • 4
  • 1
    Doesn't look like a constructor to me. Constructors must have the same name as the class they're defined in and they don't have a return type. – PakkuDon Apr 21 '15 at 13:25
  • 2
    It's just an unusually-named method. – Jon Skeet Apr 21 '15 at 13:26
  • I am curious about where you found this example? If you found it in a book, I would suggest to stop reading it right away. If someone who claims to know Java showed you this example, go as far away as possible from them as possible before it's not too late. – Chetan Kinger Apr 21 '15 at 13:30
  • That's a factory that generates only one object (a.k.a. Singleton) – Nir Alfasi Apr 21 '15 at 13:32
  • 1
    Underscore used to be an allowable (but not recommended) identifier pre-Java 8. Here's an [extreme case](http://stackoverflow.com/questions/15648312/what-is-the-underscore-actually-doing-in-this-java-code) – Reimeus Apr 21 '15 at 13:35

2 Answers2

6

No, it's just a very poorly named method. I recall another similar question recently, that quoted some documentation saying that even though a single underscore is a legal name, it shouldn't be used.

In this case it seems that the class is a Singleton, and the method that's usually named getInstance() has been shortened to _().

Kayaman
  • 72,141
  • 5
  • 83
  • 121
0

It's a funny construct that you have here. the name of the function is '_'.

So you have something like UserRequestCache._() that return a UserRequestCache.

Nothing to do with some weird Java 'magic'

JFPicard
  • 5,029
  • 3
  • 19
  • 43