Skip to content

Instantly share code, notes, and snippets.

@soverby
Last active March 17, 2017 12:47
Show Gist options
  • Save soverby/4977dec06a65e2de80a5e413eee4c427 to your computer and use it in GitHub Desktop.
Save soverby/4977dec06a65e2de80a5e413eee4c427 to your computer and use it in GitHub Desktop.
I needed a way to manage a limited pool of some resource across many threads. There are a few things about this that bug me, it's got some smells but it's 'ok' as an implementation imo.
package com.soverby.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;
public class AccessPool<T> {
private final Map<ReentrantLock, T> resourceMap = new HashMap<>();
private final ReentrantLock acquireResourceLock = new ReentrantLock();
private final Semaphore semaphore;
public AccessPool(List<T> resourceList) {
resourceList.forEach(t -> resourceMap.put(new ReentrantLock(), t));
semaphore = new Semaphore(resourceList.size());
}
public T acquire() {
try {
semaphore.acquire(1);
acquireResourceLock.lock();
try {
T resource = null;
// Get the first available
for (ReentrantLock lock : resourceMap.keySet()) {
if (!lock.isLocked()) {
lock.lock();
resource = resourceMap.get(lock);
break;
}
}
} finally {
acquireResourceLock.unlock();
}
if (resource == null) {
throw new RuntimeException("Resource is null in AccessPool::get....");
}
return resource;
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
return null;
}
public void relinquish(T acquired) {
for (ReentrantLock lock : resourceMap.keySet()) {
T resource = resourceMap.get(lock);
if (resource == acquired) {
lock.unlock();
semaphore.release(1);
}
}
}
}
@JackDBrown
Copy link

Hey, could you possible teach me Java Script?

@soverby
Copy link
Author

soverby commented Mar 17, 2017

There are tons of great online courses and resources to do that. Try Udemy or Coursera. Frankly JavaScript isn't a great language to learn as your first language imo. I'd learn Java first. Writing bad javascript is very easy, writing great javascript is not easy. Java is like JavaScript on training wheels. Plus learning a strongly typed object oriented language before moving on to an extremely flexible functional language likd javascript will end up helping you in the long run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment