Skip to content

Instantly share code, notes, and snippets.

@vtermanis
Created November 11, 2021 10:53
Show Gist options
  • Save vtermanis/f5dbe68ccdf6bf6a6af1123bbcb723bf to your computer and use it in GitHub Desktop.
Save vtermanis/f5dbe68ccdf6bf6a6af1123bbcb723bf to your computer and use it in GitHub Desktop.
public class Example2 {
static class NotFoundException extends Exception {}
static class Database {
java.util.Map<String,Integer> entries;
Database() {
entries = java.util.Collections.synchronizedMap(new java.util.HashMap<String,Integer>());
}
int Get(String key) throws NotFoundException{
Integer value;
if ((value = entries.get(key)) == null) {
throw new NotFoundException();
}
return value;
}
void Set(String key, int value) {
entries.put(key, value);
}
}
static class TheAPI {
Database db;
TheAPI(Database db) {
this.db = db;
}
void Set(String key, int initialValue) {
db.Set(key, initialValue);
}
int Get(String key) throws NotFoundException {
return db.Get(key);
}
int AddTo(String key, int value) throws NotFoundException {
int newValue = db.Get(key) + value;
db.Set(key, newValue);
return newValue;
}
int MultiplyBy(String key, int value) throws NotFoundException {
int newValue = db.Get(key) * value;
db.Set(key, newValue);
return newValue;
}
}
/* -------------------------------------------------- */
static TheAPI api = new TheAPI(new Database());
static {
api.Set(new String("fish"), 5);
}
public static void main(String args[]) throws NotFoundException {
Runnable
adder = () -> {
try {
api.AddTo(new String("fish"), 3);
} catch (NotFoundException e) {}
},
multiplier = () -> {
try {
api.MultiplyBy(new String("fish"), 2);
} catch (NotFoundException e) {}
};
Thread
t1 = new Thread(adder),
t2 = new Thread(multiplier);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {}
System.out.printf("Result: %d\n", api.Get(new String("fish")));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment