summaryrefslogtreecommitdiff
path: root/bdb/rpc_server/java/FreeList.java
blob: e831c46613756f3c8a72e5681ca4b3589d6b980c (plain)
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*-
 * See the file LICENSE for redistribution information.
 *
 * Copyright (c) 2001-2002
 *      Sleepycat Software.  All rights reserved.
 *
 * $Id: FreeList.java,v 1.3 2002/08/09 01:56:09 bostic Exp $
 */

package com.sleepycat.db.rpcserver;

import java.util.*;

/**
 * Keep track of a list of objects by id with a free list.
 * Intentionally package-protected exposure.
 */
class FreeList
{
	class FreeIndex {
		int index;
		FreeIndex(int index) { this.index = index; }
		int getIndex() { return index; }
	}

	Vector items = new Vector();
	FreeIndex free_head = null;

	public synchronized int add(Object obj) {
		int pos;
		if (free_head == null) {
			pos = items.size();
			items.addElement(obj);
			if (pos % 1000 == 0)
				DbServer.err.println(this + " grew to size " + pos);
		} else {
			pos = free_head.getIndex();
			free_head = (FreeIndex)items.elementAt(pos);
			items.setElementAt(obj, pos);
		}
		return pos;
	}

	public synchronized void del(int pos) {
		Object obj = items.elementAt(pos);
		if (obj != null && obj instanceof FreeIndex)
			throw new NoSuchElementException("index " + pos + " has already been freed");
		items.setElementAt(free_head, pos);
		free_head = new FreeIndex(pos);
	}

	public void del(Object obj) {
		del(items.indexOf(obj));
	}

	public Object get(int pos) {
		Object obj = items.elementAt(pos);
		if (obj instanceof FreeIndex)
			obj = null;
		return obj;
	}

	public LocalIterator iterator() {
		return new FreeListIterator();
	}

	/**
	 * Iterator for a FreeList.  Note that this class doesn't implement
	 * java.util.Iterator to maintain compatibility with Java 1.1
	 * Intentionally package-protected exposure.
	 */
	class FreeListIterator implements LocalIterator {
		int current;

		FreeListIterator() { current = findNext(-1); }

		private int findNext(int start) {
			int next = start;
			while (++next < items.size()) {
				Object obj = items.elementAt(next);
				if (obj == null || !(obj instanceof FreeIndex))
					break;
			}
			return next;
		}

		public boolean hasNext() {
			return (findNext(current) < items.size());
		}

		public Object next() {
			current = findNext(current);
			if (current == items.size())
				throw new NoSuchElementException("enumerated past end of FreeList");
			return items.elementAt(current);
		}

		public void remove() {
			del(current);
		}
	}
}