i was trying to solve a problem regarding list.add
and list.remove
with combination in using Thread in java.
Lets assume we play with Stack
this is my Stack definition class..
import java.util.ArrayList;
public class Stack {
private int size;
private int maxSize;
private final ArrayList<Object> list;
public Stack(int size) {
this.size = 0;
this.maxSize = size;
this.list = new ArrayList<Object>(size);
}
public boolean push(Object o) {
if (size >= maxSize) {
return false;
}
this.list.add(0, o);
this.size++;
return true;
}
public Object pop() {
Object o;
if (this.size == 0) {
return null;
}
o = this.list.remove(0);
this.size--;
return o;
}
public int size() {
return this.size;
}
}
And here is how we using the stack in thread in Java
final Stack stack = new Stack(4);
for(int i = 0; i < 10000; i++) {
final String data = "hello " + i;
final int x = i;
new Thread(new Runnable() {
public void run() {
if(x % 2 == 0) {
System.out.println(stack.push(data));
} else {
System.out.println(stack.pop());
}
}
}).start();
}
So basically we just create 10000 thread to manipulate Stack object.
stack.push
resulted True (if stack not yet full) or false (if stack already full)
stack.pop
resulted null if stack is empty
And the question is : Whats wrong with Stack implementation above and how to fix it?
My analysis so far is how thread running in java. Thread run in parallel instead sequentially. I tried to execute the program and sometimes exception IndexOutOfBounds
pops out. If my analysis is true (or close), is there a way to evade the exception? Maybe include some checking method in Stack class?
If my analysis is false, so what's wrong with the implementation above? and how to fix it?