Edit: I am trying to create a shared database connection pool for all sessions of a web application. A different post said the best way to create a servlet context object was by having the init listener create it. I am however unclear on how to make this object available for use by my servlet.
-
1Can you give us some code that might help explain your problem? – Keppil Jan 17 '14 at 18:14
-
1Can't you use an empty constructor? And then check for fields to know if it has been initialized? what is the point of final though? – Sherif elKhatib Jan 17 '14 at 18:15
-
Ask someone on StackOverflow to write your initialization code for you. – Hot Licks Jan 17 '14 at 18:27
5 Answers
One solution is using a private holder class:
public class SomeClass {
private static class ResourceHolder {
private static final Resource INSTANCE = new Resource();
}
public static Resource getInstance() {
return ResourceHolder.INSTANCE;
}
}
the instance will be initialized when SomeClass.getInstance()
is called the first time.
-
This is referred to as the [Singleton Holder](http://en.wikipedia.org/wiki/Singleton_pattern#Initialization_On_Demand_Holder_Idiom) pattern. It's clean and threadsafe, but does make for code that is difficult to test and modularize. It should therefore be used with caution. – dimo414 Jan 17 '14 at 18:34
-
would it be possible to lazy initialize this pattern, like I said I don't have access to the arguments necessary to create this object on load. – user3056052 Jan 17 '14 at 18:59
-
-
it's a database connection? static because db connections are a limited resource, final because I don't want it to be changed once a connection is established. As for why I am not hard coding it, because I have to pull the url and credentials from a web.xml file. – user3056052 Jan 17 '14 at 19:05
-
@user3056052 I would not do it that way at all. You should initialise one Connection pool early in your main with the appropriate settings and pass it around to whoever needs it instead of having a global variable somewhere in your code. – assylias Jan 17 '14 at 19:11
-
@assylias you helped me go down the right road though I have no main it's a Servlet. I am now storing the connection in the session and only creating one if my session doesn't have one defined. Maybe there's a better way? – user3056052 Jan 17 '14 at 19:29
-
1@user3056052 I'm not very familiar with servlets. If in doubt, you should ask a more specific question explaining what you are trying to achieve - I'm pretty sure there is a standard way of doing it and a singleton, even if it could work, is probably not the best way. – assylias Jan 17 '14 at 19:37
-
@user3056052 Many, many questions and answers have been asked about properly setting up and sharing database connections. Consider http://stackoverflow.com/questions/241454/best-way-to-manage-database-connection-for-a-java-servlet and https://www.google.com/search?q=servlet%20database%20connection – dimo414 Jan 17 '14 at 21:38
Another way you could do this is use static initialization:
public class SomeClass {
private static final Object[] CONTENT;
static {
CONTENT = new Object[SomeOtherClass.getContentSize()]; // To show you can access runtime variables
}
}
This will initialize the CONTENT
array once the class is loaded using the ClassLoader.

- 2,999
- 3
- 20
- 31
The simplest lazy initialisation is to use an enum
with one instance.
enum Singleton {
INSTANCE; // lazy initialised
}
The added problem is you want initialisation values. To handle this you can nest the class.
enum Utility {;
static MyType val;
static OtherType val2;
enum Holder {
INSTANCE;
Holder() {
// uses val and val2
}
}
public static Holder getInstance(MyType val, OtherType val2) {
Utility.val = val;
Utility.val2 = val2;
return Holder.INSTANCE; // only created the first time.
}
}
Note: this is thread safe as static block initialisation is safe.

- 525,659
- 79
- 751
- 1,130
Something like:
public static abstract class Lazy<T> {
private T t = null;
public synchronized T get() {
if (t == null) {
t = create();
}
return t;
}
protected abstract T create();
}
public static final Lazy<List<String>> lazyList = new Lazy<List<String>>(){
@Override
protected List<String> create() {
return new ArrayList<String>();
}
};

- 43,583
- 4
- 41
- 61
I'll caution you up front, what you're describing has a bit of code smell, and I suspect you'll do better to avoid this pattern entirely. A static resource that depends on external runtime state breaks all sorts of best practices about variable scope.
What you're describing, however, would best be implemented by either a Supplier
or a Future
, depending on the work involved in successfully constructing the object you need. The difference is somewhat pedantic, but you'd generally use a Future
to hold a reference that will take a long time to compute, while a Supplier
generally returns quickly. Future
also has some nice hook-ins with Java's concurrency utilities, but by the sound of it you don't need that.
You'd use a Supplier
like so:
public class GlobalState {
public static final Supplier<LazyData> MY_DATA = Suppliers.memoize(
new Supplier<LazyData>() {
public LazyData get() {
// do whatever you need to construct your object, only gets executed once needed
}
});
...
}
Suppliers.memoize()
will cache the result of the first call to the underlying Supplier
in a threadsafe way, so simply wrapping the Supplier
you define with this call prevents duplicate processing.

- 47,227
- 18
- 148
- 244