Advertisement
Guest User

Untitled

a guest
Jun 27th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. import java.util.concurrent.atomic.AtomicLong;
  2.  
  3. public class ReentrantCASLock {
  4. private AtomicLong lockingThread;
  5. private int count;
  6.  
  7. public ReentrantCASLock() {
  8. lockingThread = new AtomicLong(-1);
  9. count = 0;
  10. }
  11.  
  12. public void lock() {
  13. while (!(lockingThread.compareAndSet(-1, Thread.currentThread().getId())
  14. || lockingThread.compareAndSet(Thread.currentThread().getId(), Thread.currentThread().getId())));
  15.  
  16. count++;
  17. }
  18.  
  19. public void unlock() throws IllegalMonitorStateException {
  20. if (lockingThread.get() != Thread.currentThread().getId()) {
  21. throw new IllegalMonitorStateException();
  22. }
  23.  
  24. count--;
  25.  
  26. if (count == 0) {
  27. while (lockingThread.compareAndSet(Thread.currentThread().getId(), -1));
  28. }
  29. }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement