|
| 1 | +package sporadic.semaphore; |
| 2 | + |
| 3 | +import java.util.concurrent.Semaphore; |
| 4 | + |
| 5 | +/** |
| 6 | + * This is a small program to demo how semaphore can create trouble for us. |
| 7 | + * One rule of thumb is: |
| 8 | + * Always release what you acquire! |
| 9 | + * Copied from online. |
| 10 | + * |
| 11 | + */ |
| 12 | +//this is a bad public class name, it doesn't apply to |
| 13 | +//what this class really do, it's a name from a different class that I copied earlier. |
| 14 | +public class ConnectionLimiter { |
| 15 | + |
| 16 | + private static class DoubleResourceGrabber implements Runnable{ |
| 17 | + |
| 18 | + private Semaphore first; |
| 19 | + private Semaphore second; |
| 20 | + |
| 21 | + public DoubleResourceGrabber(Semaphore s1, Semaphore s2){ |
| 22 | + first = s1; |
| 23 | + second = s2; |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public void run() { |
| 28 | + Thread t = Thread.currentThread(); |
| 29 | + |
| 30 | + try { |
| 31 | + first.acquire(); |
| 32 | + System.out.println(t.getName() + " acquired " + first); |
| 33 | + |
| 34 | +// Thread.sleep(20);//to demo a deadlock |
| 35 | + |
| 36 | +// second.acquire(); |
| 37 | +// System.out.println(t.getName() + " acquired " + second); |
| 38 | + |
| 39 | +// second.release(); |
| 40 | +// System.out.println(t.getName() + " released " + second); |
| 41 | + |
| 42 | + first.release(); |
| 43 | + System.out.println(t.getName() + " released " + first); |
| 44 | + |
| 45 | + } catch (InterruptedException e) { |
| 46 | + e.printStackTrace(); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * @param args |
| 53 | + * @throws InterruptedException |
| 54 | + */ |
| 55 | + public static void main(String[] args) throws InterruptedException { |
| 56 | + Semaphore s1 = new Semaphore(1);//give it only 1 permit |
| 57 | + Semaphore s2 = new Semaphore(1);//give it only 1 permit as well |
| 58 | + Thread t1 = new Thread(new DoubleResourceGrabber(s1, s2)); |
| 59 | + //now reverse them, here comes the trouble |
| 60 | + Thread t2 = new Thread(new DoubleResourceGrabber(s2, s1)); |
| 61 | + |
| 62 | + t1.start(); |
| 63 | + t2.start(); |
| 64 | + |
| 65 | + t1.join(); |
| 66 | + t2.join(); |
| 67 | + System.out.println("We got lucky!"); |
| 68 | + |
| 69 | + } |
| 70 | + |
| 71 | +} |
0 commit comments