1 | package de.uka.ipd.sdq.prototype.framework.tests; |
2 | |
3 | import java.io.IOException; |
4 | |
5 | import junit.framework.Assert; |
6 | |
7 | import org.apache.log4j.ConsoleAppender; |
8 | import org.apache.log4j.Logger; |
9 | import org.apache.log4j.SimpleLayout; |
10 | import org.junit.Before; |
11 | import org.junit.Test; |
12 | |
13 | import de.uka.ipd.sdq.prototype.framework.strategies.PassiveResource; |
14 | import de.uka.ipd.sdq.prototype.framework.strategies.PassiveResourceRegistry; |
15 | |
16 | public class PassiveResourcesTest { |
17 | private static final int CAPACITY = 1; |
18 | private static final String PR1 = "pr1"; |
19 | private static final String PR2 = "pr2"; |
20 | |
21 | @Before |
22 | public void initialise(){ |
23 | PassiveResource pr1 = new PassiveResource(CAPACITY,PR1); |
24 | PassiveResource pr2 = new PassiveResource(CAPACITY+1,PR2); |
25 | PassiveResourceRegistry.singleton().addPassiveResource(pr1); |
26 | PassiveResourceRegistry.singleton().addPassiveResource(pr2); |
27 | |
28 | Logger.getLogger(PassiveResource.class.getName()) |
29 | .addAppender(new ConsoleAppender(new SimpleLayout())); |
30 | } |
31 | |
32 | @Test |
33 | public void testPassiveResources() throws IOException, InterruptedException { |
34 | ThreadGroup tg = new ThreadGroup("Acquiring Threads"); |
35 | |
36 | PassiveResourceRegistry.singleton().getResource(PR1).acquire(); |
37 | |
38 | AcquiringThread at = new AcquiringThread(); |
39 | new Thread(tg, at).start(); |
40 | |
41 | Thread.sleep(1000); |
42 | Assert.assertTrue(tg.activeCount() == 1); |
43 | |
44 | PassiveResourceRegistry.singleton().getResource(PR1).release(); |
45 | |
46 | Thread.sleep(100); |
47 | Assert.assertTrue(tg.activeCount() == 0); |
48 | |
49 | PassiveResourceRegistry.singleton().getResource(PR2).acquire(); |
50 | PassiveResourceRegistry.singleton().getResource(PR2).acquire(); |
51 | PassiveResourceRegistry.singleton().getResource(PR2).release(); |
52 | PassiveResourceRegistry.singleton().getResource(PR2).release(); |
53 | |
54 | TryingThread tt = new TryingThread(); |
55 | new Thread(tg, tt).start(); |
56 | |
57 | Thread.sleep(100); |
58 | |
59 | } |
60 | |
61 | class TryingThread implements Runnable { |
62 | public void run() { |
63 | PassiveResourceRegistry.singleton().getResource(PR2).acquire(); |
64 | PassiveResourceRegistry.singleton().getResource(PR2).acquire(); |
65 | PassiveResourceRegistry.singleton().getResource(PR2).acquire(); |
66 | |
67 | Assert.assertTrue(false); |
68 | } |
69 | } |
70 | |
71 | class AcquiringThread implements Runnable { |
72 | public void run() { |
73 | PassiveResourceRegistry.singleton().getResource(PR1).acquire(); |
74 | Logger.getLogger(PassiveResource.class.getName()).debug("ACQUIRED! "); |
75 | } |
76 | } |
77 | } |