Skip to content

Instantly share code, notes, and snippets.

@syaau
Created December 16, 2015 05:58
Show Gist options
  • Save syaau/1da8a6c266b465562953 to your computer and use it in GitHub Desktop.
Save syaau/1da8a6c266b465562953 to your computer and use it in GitHub Desktop.
The Java Initializer Pattern for Thread Safe initialization from mutliple sources
/* 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);
}
}
@syaau
Copy link
Author

syaau commented Dec 16, 2015

The Initializer Code

public class Initializer<T extends InitProcess<?>> {
  private final List<T> processes = new ArrayList<>();

  public Initializer(T process) {
    processes.add(process);
  }

  void add(T process) {
    processes.add(process);
  }

  public Iterator<T> getProcesses() {
    return processes.iterator();
  }
}

The InitProcess code

public interface InitProcess<T> {
  void execute(T source);
}

Example Usage

CollectionHolder holder = new CollectionHolder(source -> {
  source.addObject(1);
  source.addObject(2);
});

holder.addObject(3); //this will throw an exception

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment