1 /**********************************************************************
2 * ThreadQueue.java
3 * created on 07.08.2004 by netseeker
4 * $Source: /cvsroot/ejoe/EJOE/src/de/netseeker/ejoe/concurrent/ThreadQueue.java,v $
5 * $Date: 2006/03/21 18:14:34 $
6 * $Revision: 1.18 $
7 *
8 * ====================================================================
9 *
10 * Copyright 2005-2006 netseeker aka Michael Manske
11 *
12 * Licensed under the Apache License, Version 2.0 (the "License");
13 * you may not use this file except in compliance with the License.
14 * You may obtain a copy of the License at
15 *
16 * http://www.apache.org/licenses/LICENSE-2.0
17 *
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
23 * ====================================================================
24 *
25 * This file is part of the ejoe framework.
26 * For more information on the author, please see
27 * <http://www.manskes.de/>.
28 *
29 *********************************************************************/
30
31 package de.netseeker.ejoe.concurrent;
32
33 import java.util.LinkedList;
34 import java.util.logging.Level;
35 import java.util.logging.Logger;
36
37 /***
38 * @author netseeker aka Michael Manske
39 * @since 0.3.0
40 */
41 final class ThreadQueue
42 {
43 private static final Logger logger = Logger.getLogger(ThreadQueue.class.getName());
44
45 private final LinkedList list = new LinkedList();
46
47 private long defaultTimeout = 10000;
48
49 public ThreadQueue()
50 {
51 }
52
53 /***
54 * Returns the current number of object in the queue
55 */
56 public synchronized int size()
57 {
58 return list.size();
59 }
60
61 /***
62 * adds a new object to the end of the queue. At least one thread will be
63 * notified.
64 */
65 public synchronized void add(Runnable thread)
66 {
67 list.add(thread);
68 notify();
69 }
70
71 /***
72 * Removes the first object from the queue, blocking until one is available.
73 * Note that this method will never return null and could block forever.
74 */
75 public synchronized Runnable remove()
76 {
77 Runnable answer = removeNoWait();
78 if (answer == null)
79 {
80 try
81 {
82 wait(defaultTimeout);
83 }
84 catch (InterruptedException e)
85 {
86 logger.log(Level.WARNING, "Thread was interrupted: ", e);
87 }
88 answer = removeNoWait();
89 }
90 return answer;
91 }
92
93 /***
94 * Removes the first object from the queue without blocking. This method
95 * will return immediately with an item from the queue or null.
96 *
97 * @return the first thread removed from the queue or null if the queue is
98 * empty
99 */
100 private synchronized Runnable removeNoWait()
101 {
102 if (!list.isEmpty())
103 {
104 return (Runnable) list.removeFirst();
105 }
106
107 return null;
108 }
109 }