summaryrefslogtreecommitdiff
path: root/src/actors/scala/actors/threadpool/helpers/FIFOWaitQueue.java
blob: 432b851f3eff8926265ce7b5d06d9d93420e4a73 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package scala.actors.threadpool.helpers;

import java.util.Collection;
import java.util.ArrayList;
import java.util.List;

/**
 * Simple linked list queue used in FIFOSemaphore.
 * Methods are not synchronized; they depend on synch of callers.
 * Must be public, since it is used by Semaphore (outside this package).
 * NOTE: this class is NOT present in java.util.concurrent.
 **/

public class FIFOWaitQueue extends WaitQueue implements java.io.Serializable {

    private final static long serialVersionUID = 2416444691925378811L;

    protected transient WaitNode head_ = null;
    protected transient WaitNode tail_ = null;

    public FIFOWaitQueue() {}

    public void insert(WaitNode w) {
        if (tail_ == null)
            head_ = tail_ = w;
        else {
            tail_.next = w;
            tail_ = w;
        }
    }

    public WaitNode extract() {
        if (head_ == null)
            return null;
        else {
            WaitNode w = head_;
            head_ = w.next;
            if (head_ == null)
                tail_ = null;
            w.next = null;
            return w;
        }
    }

    public void putBack(WaitNode w) {
        w.next = head_;
        head_ = w;
        if (tail_ == null)
            tail_ = w;
    }

    public boolean hasNodes() {
        return head_ != null;
    }

    public int getLength() {
        int count = 0;
        WaitNode node = head_;
        while (node != null) {
            if (node.waiting) count++;
            node = node.next;
        }
        return count;
    }

    public Collection getWaitingThreads() {
        List<Thread> list = new ArrayList<Thread>();
        int count = 0;
        WaitNode node = head_;
        while (node != null) {
            if (node.waiting) list.add(node.owner);
            node = node.next;
        }
        return list;
    }

    public boolean isWaiting(Thread thread) {
        if (thread == null) throw new NullPointerException();
        for (WaitNode node = head_; node != null; node = node.next) {
            if (node.waiting && node.owner == thread) return true;
        }
        return false;
    }

}