Created
May 13, 2015 14:00
-
-
Save spitz-dan-l/1b99486c0448e015b91d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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