fork(1) download
  1. import java.util.concurrent.ConcurrentHashMap;
  2.  
  3. /**
  4.  * User: And390
  5.  * Date: 14.06.14
  6.  * Time: 0:21
  7.  */
  8. public class Main {
  9.  
  10. private static final ConcurrentHashMap<Object, Object> LOCKS = new ConcurrentHashMap<Object, Object> ();
  11.  
  12. public static void saveSomethingImportantToDataBase(Object id) {
  13. Object newLock = new Object ();
  14. Object lock = LOCKS.putIfAbsent(id, newLock);
  15. synchronized (lock!=null ? lock : newLock) {
  16. System.out.println("begin");
  17. try { Thread.sleep(1000); } catch (InterruptedException e) {}
  18. System.out.println("end");
  19. }
  20. try { Thread.sleep(500); } catch (InterruptedException e) {} // ! this is shows error in multi-thread environment
  21. LOCKS.remove(id);
  22. }
  23.  
  24. public static Thread startTestThread() {
  25. Thread thread = new Thread() { public void run() { saveSomethingImportantToDataBase(1); } };
  26. thread.start();
  27. return thread;
  28. }
  29.  
  30. public static void main(String[] args) throws Exception {
  31. startTestThread();
  32. startTestThread();
  33. Thread.sleep(1000+500+100);
  34. startTestThread();
  35. }
  36.  
  37. }
  38.  
Success #stdin #stdout 0.08s 380864KB
stdin
Standard input is empty
stdout
begin
end
begin
begin
end
end