Skip to content

Instantly share code, notes, and snippets.

@spitz-dan-l
Created May 13, 2015 14:00
Show Gist options
  • Save spitz-dan-l/1b99486c0448e015b91d to your computer and use it in GitHub Desktop.
Save spitz-dan-l/1b99486c0448e015b91d to your computer and use it in GitHub Desktop.
public class SynchronizedCounter {
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
}
public void updateWordCount(HashMap<String, SynchronizedCounter> counts, String wordToUpdate){
if (counts.containsKey(wordToUpdate)) {
SynchronizedCounter current_count = counts.get(wordToUpdate);
current_count.increment();
} else { //still vulnerable here to race conditions. just pay attention to above
SynchronizedCounter new_count = new SynchronizedCounter();
new_count.increment();
counts.put(wordToUpdate, new_count);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment