Not sure how I can use the link you gave me :o(
To be more clear, I have 2 threads (it could be more but I would use first 2)
Thread B is started (it's in fact a listener on a UDP port).
Thread A does sends a packet through the UDP port.
Thread A now must wait that Thread B tell him: "I have received something for you"
Thread A starts again to work.
here is the way I have finally chosen:
1. Each time, thread B will receive a UDP packet, it will save the data in a list.
2. After thread A has sent his packet over UDP, it will look each 500 ms in the list to see if an answer is arrived for him.
I do not know if this is the most efficient way but at least it works.
Thx it helps.
I reproduced the producer / consumer scheme ( I still need to test it ;o) ). In the put method, I did not use the available value as while statement ( as my producer should not wait that the list is empty to write new element). The producer just needs to get the lock, update the list and release the lock (at least this is my understanding). The consumer needs to wait for data to be available in the list and then it can consume it but only if the data is for him.
It gives something like below:
public class RadiusPacketWaitingList {
private boolean available = false;
private Map<Integer, DatagramPacket> packetList;
private Lock aLock = new ReentrantLock();
private Condition condVar = aLock.newCondition();
public void put( int identifier, DatagramPacket packet) {
// Get the lock
aLock.lock();
try {
this.packetList.put(identifier,packet);
available = true;
} finally {
// Release the lock
aLock.unlock();
}
}
public DatagramPacket get(int identifier) {
DatagramPacket packet = null;
// Get the lock
aLock.lock();
try {
while ( this.available == false ) {
// Wait for the listener to put an element in the map
try {
condVar.await();
} catch (InterruptedException e) {}
}
available = false;
if ( this.packetList.containsKey(identifier) ) {
System.out.println("I have an answer for me!!");
// Get the packet
packet = this.packetList.get(identifier);
// Remove the entry from the list
this.packetList.remove(identifier);
// Is there other elements in the list?
if ( this.packetList.size() > 0 ) {
// There is still data in the list
available = true;
}
// Notify the other thread that I have completed my task
condVar.signalAll();
} else {
// The data is not for me and so must be available for another thread
available = true;
// Notify the other thread that I have completed my task
condVar.signalAll();
}
} finally {
// Release the lock
aLock.unlock();
}
return packet;
}
}
Does it seem right?