-
Notifications
You must be signed in to change notification settings - Fork 0
/
MemoryManager.java
79 lines (73 loc) · 2.2 KB
/
MemoryManager.java
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
// -------------------------------------------------------------------------
/**
* A class that manages records stored in a memory pool.
*
* @author Joshua Rush
* @author Benjamin Roble
* @version Aug 28, 2011
*/
public class MemoryManager
{
private byte[] pool;
private FreeBlockList freeList;
/**
* Creates a memory manager with a memory pool of the
* specified size.
* @param poolsize the size of the pool of free memory
*/
public MemoryManager(int poolsize)
{
pool = new byte[poolsize];
freeList = new FreeBlockList(poolsize);
}
/**
* Inserts a record and returns its position Handle.
* @param space the record to be inserted
* @param size the size of the record being inserted
* @return the position Handle of the inserted record
*/
public Handle insert(byte[] space, int size)
{
int position = freeList.use(size);
System.arraycopy(space, 0, pool, position, size);
return new Handle(position);
}
/**
* Frees a block at the indicated posHandle.
* Merge adjacent blocks if necessary.
* @param theHandle the position Handle of the record
* to be removed
*/
public void remove(Handle theHandle)
{
int position = theHandle.getPosition();
Byte sizeByte = new Byte(pool[position]);
int sizeInt = sizeByte.intValue();
//clears the pool of the record
for (int i = position; i <= position + sizeInt; i++)
{
pool[i] = 0;
}
freeList.free(sizeInt, position);
}
/**
* Return the record with the indicated position Handle,
* up to size bytes.
* @param theHandle the posHandle of the record to be returned
* @param size the size of the of the record to be returned
* @return the record from posHandle up to size
*/
public byte[] get(Handle theHandle, int size)
{
byte[] space = new byte[size];
System.arraycopy(freeList, theHandle.getPosition(), space, 0, size);
return space;
}
/**
* Prints out a representation of the nodes in the freeblock list.
*/
public void dump()
{
freeList.toString();
}
}