fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.util.concurrent.*;
  5. import java.util.concurrent.locks.*;
  6. import java.lang.*;
  7. import java.io.*;
  8.  
  9. /* Name of the class has to be "Main" only if the class is public. */
  10. class Ideone {
  11.  
  12. private static final ConcurrentHashMap<String, Semaphore> map = new ConcurrentHashMap<>();
  13.  
  14. private static void callLongRunningMethod() {
  15. System.out.println("Start " + Thread.currentThread().getName());
  16. try {
  17. Thread.sleep(500);
  18. } catch (InterruptedException e) {
  19. Thread.currentThread().interrupt();
  20. throw new RuntimeException(e);
  21. }
  22. System.out.println("End " + Thread.currentThread().getName());
  23. }
  24.  
  25. public static void test(String hash) {
  26. Semaphore s = map.computeIfAbsent(hash, k -> new Semaphore(1));
  27. try {
  28. s.acquire();
  29. } catch (InterruptedException e) {
  30. throw new RuntimeException(e);
  31. }
  32. try {
  33. callLongRunningMethod();
  34. } finally {
  35. s.release();
  36. map.remove(hash, s);
  37. }
  38. }
  39.  
  40. public static void main(String[] args) throws java.lang.Exception {
  41. new Thread(
  42. () -> {
  43. test("");
  44. test("");
  45. })
  46. .start();
  47. new Thread(
  48. () -> {
  49. test("");
  50. test("");
  51. })
  52. .start();
  53. // your code goes here
  54. }
  55. }
  56.  
Success #stdin #stdout 0.19s 321344KB
stdin
Standard input is empty
stdout
Start Thread-0
End Thread-0
Start Thread-0
Start Thread-1
End Thread-0
End Thread-1
Start Thread-1
End Thread-1