1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package net.sf.magicproject.network;
20
21 /***
22 * @author <a href="mailto:fabdouglas@users.sourceforge.net">Fabrice Daugan </a>
23 * @since 0.3
24 */
25 public class MMiniPipe {
26
27 /***
28 * Create an instance of MMiniPipe initializing the token to free. Means that
29 * the next call to method <code>take()</code> would'nt block the calling
30 * thread.
31 *
32 * @see MMiniPipe#take()
33 * @see #MMiniPipe(boolean)
34 */
35 public MMiniPipe() {
36 this(false);
37 }
38
39 /***
40 * Create an instance of MMiniPipe initializing the token to the specified
41 * boolean. Means that the next call to method <code>take()</code> would'nt
42 * block the calling thread only if the specified <code>taken</code> is
43 * false.
44 *
45 * @param taken
46 * one token critical resource
47 * @see MMiniPipe#take()
48 */
49 public MMiniPipe(boolean taken) {
50 this.taken = taken;
51 }
52
53 /***
54 * Try to take this token. If the token is already token, the current thread
55 * would be blocked until a threadd release the requested token.
56 */
57 public synchronized void take() {
58 try {
59 while (taken) {
60 wait(200);
61 }
62 taken = true;
63 } catch (InterruptedException e) {
64 System.out.println("mini pipe error");
65
66 }
67 }
68
69 /***
70 * Try to take this token. If the token is already token, the current thread
71 * would be blocked until a threadd release the requested token.
72 *
73 * @return true if has been token.
74 */
75 public synchronized boolean takeNoBlock() {
76 if (!taken) {
77 taken = true;
78 return false;
79 }
80 return false;
81 }
82
83 /***
84 * Try to take this token. If the token is already token, the current thread
85 * would be blocked until a threadd release the requested token.
86 */
87 public synchronized void release() {
88 taken = false;
89 notify();
90 }
91
92 /***
93 * This boolean represents the token. When it's value is <code>false</code>
94 * that's mean the token is free, so any thread can take it without being
95 * blocked. When it' value is <code>true</code> the next thread would take
96 * this token would be blocked until the current owner release it.
97 */
98 protected boolean taken;
99
100 }