Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chanwookpark/c3cde0e1647dae735b2d to your computer and use it in GitHub Desktop.
Save chanwookpark/c3cde0e1647dae735b2d to your computer and use it in GitHub Desktop.
Striped Lock 샘플 코드
package striped;
import com.google.common.util.concurrent.Striped;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Semaphore;
/**
* Created by chanwook on 2014. 7. 16..
*/
public class SimpleConcurrentWorker {
private Striped<Semaphore> stripedSemaphores = Striped.lazyWeakSemaphore(10, 1);
private Map<String, Integer> data = new HashMap<String, Integer>();
public void concurrentDoing(String key) throws Exception {
Semaphore s = stripedSemaphores.get(key);
s.acquire(); // lock 얻기
try {
// 안전한 작업 공간..
put(key);
// 안전한 작업 공간..
} finally {
// lock 해제
s.release();
}
}
public void dontConcurrentDoing(String key) throws Exception {
put(key);
}
private void put(String key) {
Integer c = data.get(key);
if (c != null) {
data.put(key, ++c);
} else {
data.put(key, 0);
}
}
public Map<String, Integer> getData() {
return data;
}
}
package striped;
import org.junit.Test;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by chanwook on 2014. 7. 16..
*/
public class StripedTests {
SimpleConcurrentWorker w = new SimpleConcurrentWorker();
@Test
public void simpleStriped() throws Exception {
for (int i = 0; i < 100; i++) {
String key = String.valueOf(i / 5);
System.out.println(key + " 키로 요청");
// w.concurrentDoing(key);
w.dontConcurrentDoing(key);
}
}
@Test
public void doingMultiThread() throws InterruptedException {
final int threadCount = 10;
ExecutorService pool = Executors.newFixedThreadPool(threadCount);
for (int i = 0; i < 100; i++) {
final String key = String.valueOf(i / 5);
pool.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(100);
// w.dontConcurrentDoing(key);
w.concurrentDoing(key);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Thread.sleep(10000L);
pool.shutdown();
Map<String, Integer> data = w.getData();
for (Map.Entry<String, Integer> e : data.entrySet()) {
System.out.println(e.getKey() + ", " + e.getValue());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment