Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created May 9, 2011 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rklemme/962538 to your computer and use it in GitHub Desktop.
Save rklemme/962538 to your computer and use it in GitHub Desktop.
Example implementation of thread safe 1:n association (untested though).
package clj;
import java.util.HashSet;
import java.util.Set;
/**
* Example code.
*
* @author rklemme
* @see <a href="https://groups.google.com/group/comp.lang.java.programmer/browse_frm/thread/295e9e9fb6b3e489">comp.lang.java.programmer</a>
*/
public class TskWp {
/** A Task belongs to at most 1 {@link Workspace}. */
public static final class Task {
private Workspace workspace;
public synchronized Workspace getWorkspace() {
return workspace;
}
synchronized void setWorkspace(Workspace workspace) {
this.workspace = workspace;
}
}
/** A Workspace can have arbitrary many {@link Task Tasks}. */
public static final class Workspace {
private final Set<Task> tasks = new HashSet<Task>();
public void addTask(Task t) {
synchronized (t) {
final Workspace old = t.getWorkspace();
if (old != this) {
// relationship changes
if (old != null) {
old.removeTask(t);
}
assert t.getWorkspace() == null;
synchronized (tasks) {
tasks.add(t);
t.setWorkspace(this);
}
}
}
}
public void removeTask(Task t) {
synchronized (t) {
final Workspace old = t.getWorkspace();
if (old != this) {
throw new IllegalStateException("Not owner");
}
synchronized (tasks) {
tasks.remove(t);
t.setWorkspace(null);
}
}
}
/**
* Get all tasks.
*
* @return a copy of the collection to avoid concurrency issues and CME.
*/
public Set<Task> getTasks() {
synchronized (tasks) {
return new HashSet<Task>(tasks);
}
}
/**
* Anything to do?
*
* @return <code>true</code> if there are tasks.
*/
public boolean hasTasks() {
synchronized (tasks) {
return !tasks.isEmpty();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment