I have a class that extends ArrayList. I have another class called "Elem" that works as elements for the ArrayList. Multiple threads will work on this list.
When I get an element from the ArrayList I would like to lock only this element so another thread can delete other elements in the list.
I have made this method for getting and locking an element:
public String get(int id)
{
String res ="No such file, try command list";
int size = this.size();
for (int i = 0; i<size;i++)
{
Elem ifo = (Elem)this.get(i);
if(ifo.getId() == id)
{
synchronized(ifo)
{
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
res = ifo.getData() + " Received";
}
break;
}
}
return res;
}
I have made the operation last for 4 seconds because I test if the object is locked with the follwing delete method:
public synchronized String del(int id)
{
String res =" no file";
int size = this.size();
for (int i = 0; i<size;i++)
{
Elem ifo = (Elem)this.get(i);
if(ifo.getId() == id)
{
super.remove(ifo);
res = ifo.getId() + " deleted!";
break;
}
}
return res;
}
But when I run the program and start reading an element that I try to delete at the same time it gets deleted! Why does the "del" method not block until the element has been read?