Skip to content

Instantly share code, notes, and snippets.

@adohe-zz
Created July 20, 2014 07:07
Show Gist options
  • Select an option

  • Save adohe-zz/be0f770c599c7bea9936 to your computer and use it in GitHub Desktop.

Select an option

Save adohe-zz/be0f770c599c7bea9936 to your computer and use it in GitHub Desktop.
publish and escape problem in Java
package com.ado.java;
class Event {
public Event() {
}
}
abstract class EventListener {
public abstract void onEvent(Event event);
}
class EventSource {
public void registerListener(EventListener listener) {
// Stuff
}
}
/**
* Register event listener or Start new thread safely in
* the constructor
*/
public class SafeListener {
private final EventListener listener;
private void doSomething() {
}
private SafeListener() {
listener = new EventListener() {
public void onEvent(Event e) {
doSomething();
}
};
}
public static SafeListener newInstance(EventSource source) {
SafeListener safeListener = new SafeListener();
source.registerListener(safeListener.listener);
return safeListener;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment