Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Problems with synchronizing an element in an array

807569Sep 12 2006 — edited Sep 12 2006
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?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 10 2006
Added on Sep 12 2006
20 comments
603 views