Search code examples
javasyntaxcurly-braces

Code with curly braces in/after "new"?


private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() {
    public Connection initialValue() { 
         return DriverManager.getConnection(DB_URL);
    }
};

I don't understand what's going on in the part that's within the stars. Is that a way to insert a method into a class?


Solution

  • The initialValue() method of ThreadLocal is just a way to construct a ThreadLocal holding a value other than null.

    Edit: Oh, I see that's not what you're asking about. What you have there is the same as if you did:

    public class MyOwnThreadLocal extends ThreadLocal {
        public Connection initialValue() {
            return DriverManager.getConnection(DB_URL);
        }
    }
    

    Except your version doesn't require a completely separate class definition--hence it's called an "anonymous class".