Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Thread Synchronization

Status
Not open for further replies.

fatcodeguy

Programmer
Feb 25, 2002
281
0
0
CA
Hi,

I have several threads that are trying to access a single vector. Some threads want to add elements to the vector, others want to get elements from the vector.

I've implemented the following
Code:
public synchronized String get() {
   if (webList.size() == 0) {
      try {
         wait();
      } catch (InterruptedException e) { }
   }
   notifyAll();
   return (String)webList.remove(0);
}

Code:
public synchronized void put(String fileName) {
   webList.add(fileName);
}

The get method gets the objects from the vector (webList) and the put method adds to the vector.

It works perfectly with just one thread, and ALMOST (i hate almost) works with more than one thread. Sometimes the process finishes, sometimes it blocks.

Any suggestions?

Thanks,
 
What does notifyAll(); do ? I expect that is where your locks are occuring ...

--------------------------------------------------
Free Database Connection Pooling Software
 
This from Java's Thread Synchrnoization tutorial (
The notifyAll method wakes up all threads waiting on the object in question (in this case, the CubbyHole). The awakened threads compete for the lock. One thread gets it, and the others go back to waiting. The Object class also defines the notify method, which arbitrarily wakes up one of the threads waiting on this object

But you're right. the notifyAll() should be in the put() method, not get().

Thanks
 
I wouldn't bother with using that method at all - the JVM will handle the mutex locks and unlocks of threads.

--------------------------------------------------
Free Database Connection Pooling Software
 
But if I have a wait() in the get method, which I need, how will the app know to un-wait when an element is put in the vector?
 
Well Vector objects are inherently synchronized, so you don't need to worry about that at all.

When you have a syncronized method, you don't need to explictly call the wait() method - this locking is done for you implicitly at the JVM level.

--------------------------------------------------
Free Database Connection Pooling Software
 
I hope that when you mean "a vector", it's java.util.Vector, that's the synchronized class.

Cheers,

Dian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top