Created
December 16, 2015 05:58
-
-
Save syaau/1da8a6c266b465562953 to your computer and use it in GitHub Desktop.
The Java Initializer Pattern for Thread Safe initialization from mutliple sources
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* An example class */ | |
public class CollectionHolder { | |
private final List collection; | |
/* A private constructor to create a shadow instance for initization */ | |
private CollectionHolder() { | |
collection = new ArrayList<>(); | |
} | |
/* The public constructor */ | |
public CollectionHolder(Initializer<InitProcess<CollectionHolder>> initializer) { | |
// A temporary instance on which the initialization takes place | |
CollectionHolder temp = new CollectionHolder(); | |
// Get all the initializers and execute each one of them | |
Iterator<InitProcess<CollectionHolder>> iterator = iniitalizer.getProcesses(); | |
while(iterator.hasNext()) { | |
iterator.next().execute(temp); | |
} | |
// Make the collection immutable at the end of the process | |
collection = Collections.unmodifiableList(temp.collection); | |
} | |
/* The initialization method */ | |
public void addObject(Object object) { | |
// this method will work only during initialization. if this method | |
// is called from elsewhere, it will throw unsupported exception | |
collection.add(object); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The Initializer Code
The InitProcess code
Example Usage