|
| 1 | +package com.oldratlee.fucking.concurrency; |
| 2 | + |
| 3 | +import java.util.concurrent.TimeUnit; |
| 4 | +import java.util.concurrent.locks.Lock; |
| 5 | +import java.util.concurrent.locks.ReentrantLock; |
| 6 | + |
| 7 | +/** |
| 8 | + * @author Beat Richartz |
| 9 | + */ |
| 10 | +public class ReentrantLockLivelockDemo { |
| 11 | + private static final Lock lock1 = new ReentrantLock(); |
| 12 | + private static final Lock lock2 = new ReentrantLock(); |
| 13 | + |
| 14 | + public static void main(String[] args) throws Exception { |
| 15 | + Thread thread1 = new Thread(ReentrantLockLivelockDemo::concurrencyCheckTask1); |
| 16 | + thread1.start(); |
| 17 | + Thread thread2 = new Thread(ReentrantLockLivelockDemo::concurrencyCheckTask2); |
| 18 | + thread2.start(); |
| 19 | + } |
| 20 | + |
| 21 | + @SuppressWarnings("InfiniteLoopStatement") |
| 22 | + private static void concurrencyCheckTask1() { |
| 23 | + System.out.println("Started concurrency check task 1"); |
| 24 | + int counter = 0; |
| 25 | + |
| 26 | + while (counter++ < 10_000) { |
| 27 | + try { |
| 28 | + if (lock1.tryLock(50, TimeUnit.MILLISECONDS)) { |
| 29 | + System.out.println("Task 1 acquired lock 1"); |
| 30 | + Thread.sleep(50); |
| 31 | + if (lock2.tryLock()) { |
| 32 | + System.out.println("Task 1 acquired lock 2"); |
| 33 | + } else { |
| 34 | + System.out.println("Task 1 failed to acquire lock 2, releasing lock 1"); |
| 35 | + lock1.unlock(); |
| 36 | + continue; |
| 37 | + } |
| 38 | + } |
| 39 | + } catch (InterruptedException e) { |
| 40 | + e.printStackTrace(); |
| 41 | + break; |
| 42 | + } |
| 43 | + |
| 44 | + break; |
| 45 | + } |
| 46 | + |
| 47 | + System.err.printf("Fuck! No meaningful work done in %s iterations of task 1.\n", counter); |
| 48 | + lock2.unlock(); |
| 49 | + lock1.unlock(); |
| 50 | + } |
| 51 | + |
| 52 | + @SuppressWarnings("InfiniteLoopStatement") |
| 53 | + private static void concurrencyCheckTask2() { |
| 54 | + System.out.println("Started concurrency check task 2"); |
| 55 | + |
| 56 | + int counter = 0; |
| 57 | + while (counter++ < 10_000) { |
| 58 | + try { |
| 59 | + if (lock2.tryLock(50, TimeUnit.MILLISECONDS)) { |
| 60 | + System.out.println("Task 2 acquired lock 2"); |
| 61 | + Thread.sleep(50); |
| 62 | + if (lock1.tryLock()) { |
| 63 | + System.out.println("Task 2 acquired lock 1"); |
| 64 | + } else { |
| 65 | + System.out.println("Task 2 failed to acquire lock 1, releasing lock 2"); |
| 66 | + lock2.unlock(); |
| 67 | + continue; |
| 68 | + } |
| 69 | + } |
| 70 | + } catch (InterruptedException e) { |
| 71 | + e.printStackTrace(); |
| 72 | + break; |
| 73 | + } |
| 74 | + |
| 75 | + break; |
| 76 | + } |
| 77 | + |
| 78 | + System.err.printf("Fuck! No meaningful work done in %s iterations of task 2.\n", counter); |
| 79 | + lock2.unlock(); |
| 80 | + lock1.unlock(); |
| 81 | + } |
| 82 | +} |
0 commit comments