Adobe Interview Question
Member Technical StaffsCountry: India
The safest way is to ensure that only one thread calls into the third-party library at a time - that is, take a mutex around EVERY call to the library. Making it so that multiple threads can use the library at once. This could be implemented using Semaphore.
class Pool {
//you have only one instance.
private static final MAX_AVAILABLE = 1;
private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
public Object getItem() throws InterruptedException {
available.acquire();
return getNextAvailableItem();
}
public void putItem(Object x) {
if (markAsUnused(x))
available.release();
}
// Not a particularly efficient data structure; just for demo
protected Object[] items = <your third pary library item here.>
protected boolean[] used = new boolean[MAX_AVAILABLE];
protected synchronized Object getNextAvailableItem() {
for (int i = 0; i < MAX_AVAILABLE; ++i) {
if (!used[i]) {
used[i] = true;
return items[i];
}
}
return null; // not reached
}
protected synchronized boolean markAsUnused(Object item) {
for (int i = 0; i < MAX_AVAILABLE; ++i) {
if (item == items[i]) {
if (used[i]) {
used[i] = false;
return true;
} else
return false;
}
}
return false;
}
}
http://docs.oracle.com/javase/1.5.0/docs/api/index.html?java/util/concurrent/Semaphore.html
May be using decorator pattern , extend the same class and add synchronization to the extended class.
- Vijay May 14, 2013