|
| 1 | +packagesporadic.semaphore; |
| 2 | + |
| 3 | +importjava.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 | +publicclassConnectionLimiter { |
| 15 | + |
| 16 | +privatestaticclassDoubleResourceGrabberimplementsRunnable{ |
| 17 | + |
| 18 | +privateSemaphorefirst; |
| 19 | +privateSemaphoresecond; |
| 20 | + |
| 21 | +publicDoubleResourceGrabber(Semaphores1,Semaphores2){ |
| 22 | +first =s1; |
| 23 | +second =s2; |
| 24 | +} |
| 25 | + |
| 26 | +@Override |
| 27 | +publicvoidrun() { |
| 28 | +Threadt =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 (InterruptedExceptione) { |
| 46 | +e.printStackTrace(); |
| 47 | +} |
| 48 | +} |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * @param args |
| 53 | + * @throws InterruptedException |
| 54 | + */ |
| 55 | +publicstaticvoidmain(String[]args)throwsInterruptedException { |
| 56 | +Semaphores1 =newSemaphore(1);//give it only 1 permit |
| 57 | +Semaphores2 =newSemaphore(1);//give it only 1 permit as well |
| 58 | +Threadt1 =newThread(newDoubleResourceGrabber(s1,s2)); |
| 59 | +//now reverse them, here comes the trouble |
| 60 | +Threadt2 =newThread(newDoubleResourceGrabber(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 | +} |