49 * <p>Semaphores are often used to restrict the number of threads than can
50 * access some (physical or logical) resource. For example, here is
51 * a class that uses a semaphore to control access to a pool of items:
52 * <pre> {@code
53 * class Pool {
54 * private static final int MAX_AVAILABLE = 100;
55 * private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
56 *
57 * public Object getItem() throws InterruptedException {
58 * available.acquire();
59 * return getNextAvailableItem();
60 * }
61 *
62 * public void putItem(Object x) {
63 * if (markAsUnused(x))
64 * available.release();
65 * }
66 *
67 * // Not a particularly efficient data structure; just for demo
68 *
69 * protected Object[] items = ... whatever kinds of items being managed
70 * protected boolean[] used = new boolean[MAX_AVAILABLE];
71 *
72 * protected synchronized Object getNextAvailableItem() {
73 * for (int i = 0; i < MAX_AVAILABLE; ++i) {
74 * if (!used[i]) {
75 * used[i] = true;
76 * return items[i];
77 * }
78 * }
79 * return null; // not reached
80 * }
81 *
82 * protected synchronized boolean markAsUnused(Object item) {
83 * for (int i = 0; i < MAX_AVAILABLE; ++i) {
84 * if (item == items[i]) {
85 * if (used[i]) {
86 * used[i] = false;
87 * return true;
88 * } else
89 * return false;
|
49 * <p>Semaphores are often used to restrict the number of threads than can
50 * access some (physical or logical) resource. For example, here is
51 * a class that uses a semaphore to control access to a pool of items:
52 * <pre> {@code
53 * class Pool {
54 * private static final int MAX_AVAILABLE = 100;
55 * private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
56 *
57 * public Object getItem() throws InterruptedException {
58 * available.acquire();
59 * return getNextAvailableItem();
60 * }
61 *
62 * public void putItem(Object x) {
63 * if (markAsUnused(x))
64 * available.release();
65 * }
66 *
67 * // Not a particularly efficient data structure; just for demo
68 *
69 * protected Object[] items = ...; // whatever kinds of items being managed
70 * protected boolean[] used = new boolean[MAX_AVAILABLE];
71 *
72 * protected synchronized Object getNextAvailableItem() {
73 * for (int i = 0; i < MAX_AVAILABLE; ++i) {
74 * if (!used[i]) {
75 * used[i] = true;
76 * return items[i];
77 * }
78 * }
79 * return null; // not reached
80 * }
81 *
82 * protected synchronized boolean markAsUnused(Object item) {
83 * for (int i = 0; i < MAX_AVAILABLE; ++i) {
84 * if (item == items[i]) {
85 * if (used[i]) {
86 * used[i] = false;
87 * return true;
88 * } else
89 * return false;
|