My question is this: How do you hold the lock on a parent for the duration that a nested child is active?
I am writing a multithreaded Java application using the Codename One development framework where I have a parent class and a nested child class. The purpose of the child class is to act as an iterator over a Vector. Now my understanding is that while the iterator is running, the vector cannot be changed.
Here's a very simple code example:
public class Parent<E> implements Collection<Object> {
private Vector<Object> objectCollection;
Parent() {
this.objectCollection = new Vector<Object>();
}
public Child<Object> iterator() {
return(new Child());
}
class Child implements Iterator<Object> {
private int index;
Child() {
this.index = 0;
}
public boolean hasNext() {
int size = this.objectCollection.size()
if (size <= 0) return(false);
if (this.index >= size) return(false);
return(true);
}
public Object next() {
Object temp = objectCollection.elementAt(this.index);
this.index++;
return(temp);
}
}
}
What I want to do is while the nested class (iterator) is instantiated, I want the parent instance locked so all other threads coming into the parent will be blocked until the thread that has the iterator is finished and releases it.
I have done some searching on this and found these questions:
Locking and synchronization between outer and inner class methods?
Acquiring inner-class lock using outer-class locks?
However, these do not exactly match my scenario. The only thing that I can think of is to use a spinlock, but that's also not recommended in Java. So basically, I am looking for a way to do this. I can code it, I just need an explanation of what to do.
EDIT:
Only one thread would have access to the iterator. I am trying to stop the parent from being modified while the iterator is active.