java


How to notify a specific thread in a multithread application


I'm developing a server app which receives RESTful request from clients and send it to a specific device in a new thread (UDP packet). Besides, it runs another thread launched by a servlet listener at the beginning of the execution, which listens the UDP packets sent from all the devices of the system.
When a client make a request from a specific device, the REST service has to launch a thread from where an UDP packet will be sent to the device, and wait for the response. When the UDP server finally receives a packet from that device (checking the ip from the packet), it has to notify the blocked thread to continue its execution and finish.
I thought about using wait(), notify() and notifyAll() methods, but, as many threads can be blocked waiting for the response of several devices, I don't see how could I notify to unblock only the desired thread (the one that made the request on the responding device). Is there a way of doing this using that methods? Any other approach? Here is some code (simplified):
SocketServletListener:
public class SocketServletListener implements ServletContextListener {
private UDPServer server;
private ServletContext context;
#Override
public void contextInitialized(ServletContextEvent sce) {
context = sce.getServletContext();
server = new UDPServer();
server.start();
}
#Override
public void contextDestroyed(ServletContextEvent sce) {
context = sce.getServletContext();
server.interrupt();
}
}
UDPServer:
public class UDPServer extends Thread {
private SocketUDPCommunication comm;
public UDPServer() {
comm = new SocketUDPCommunication();
}
#Override
public void run() {
DatagramPacket response;
try {
comm.setPort(Utils.UDP_SERVER_PORT);
comm.createSocket();
while (!Thread.currentThread().isInterrupted()) {
try {
response = comm.receiveResponse();
} catch (SocketTimeoutException e) {
continue;
}
InetAddress ip = response.getAddress();
int port = response.getPort();
byte[] byteSend = comm.discardOffset(response);
//TODO notify thread which made the request for the responding device (identified by ip)
}
} catch (IOException e) {
System.err.println("Unable to process client request: " + e.getMessage());
} catch (IllegalArgumentException ex) {
System.err.println("Illegal Argument: " + ex.getMessage());
} finally {
comm.closeConnection();
}
}
#Override
public void interrupt() {
super.interrupt();
comm.closeConnection();
}
}
DataSend.java:
#Path("dataSend")
public class DataSend {
#Context
private UriInfo context;
public DataSend() {
}
#POST
#Consumes(MediaType.APPLICATION_JSON)
public Response postJson(ForceStatus status) {
new TestExecution(status).start();
return Response.status(Response.Status.OK).build();
}
}
TestExecution:
public class TestExecution extends Thread {
private ForceStatus status;
public ExamExecution(ForceStatus status) {
this.status = status;
}
#Override
public void run() {
ProtocolStatus p = new ProtocolStatus();
byte[] s = p.createResponseFrame(status.getForce());
List<Integer> executedTest = new ArrayList<>();
//Simple UDP client
UDPClient client = new UDPClient();
.
.
.
//t is a pojo which contains the data from a battery of tests
while(!executedTest.contains(t.getTestId())) {
client.send(status.getIp(), status.getPort(), s);
//TODO wait until UDPServer thread gets the response from the device
executedTest.add(t.getTestId());
nextTest = t.getNextTestId();
t = getEntity(nextTest);
}
}
}

Related Links

Java: Constraint programming library suggestion?
isSelected() Checkbox error
Use of str.length()-1 in case of swapping a letter of a word with each other [closed]
what will cause socket write throws connection timeout exception
Apache POI get line breaks from XWPFRun
Android Display 2 fragments inside another one
Dynamic addition of column in TableView and editing cells using javafx
Java Reflection : invoking inherited methods from child class
If Else Condition not Working in Increase and Decrease Value of qty
For each save (update) hibernate envers creating revisions either changed in table or not
Starting Tomcat with CMD
org.apache.poi.EmptyFileException: The supplied file was empty (zero bytes long)
Assert 2 Lists<String> are equal ignoring order
NoSuchMethodException SoapUI Java
Why can this object access methods of it's parent class?
SQLite database already created and in Android Studio but how do I display information from the database in my application? [duplicate]

Categories

HOME
sendgrid
reserved
session
sd-card
maven-3
infragistics
microservices
sql-server-2016
ojdbc
acquia
fancybox
flyway4
bs4
android-youtube-api
fancybox-3
handsontable
hapi
iolanguage
clearcase-ucm
opentracing
finite-automata
swiftlint
amazonsellercentral
functional-testing
sylius
apache-commons-io
bootstrap-duallistbox
intel-pin
virtualdub
uninstall
gsoap
lightswitch-2013
preg-match
google-cloud-endpoints-v2
semantic-versioning
oracle-fusion-middleware
http-get
code-contracts
kendo-ui-grid
webtest
rotational-matrices
wallpaper
y86
html5-fullscreen
android-ble
ios5
scaffold
angularjs-factory
opshub
awt
ws-security
checkboxlist
smartcontracts
network-flow
blogengine.net
return-value
gabor-filter
darcs
diagnostics
sqlclient
media-player
angular-cache
infix-notation
azure-virtual-network
url-masking
thrust
nsviewcontroller
oauth2client
javax.sound.midi
django-unittest
purge
arcanist
oberon
python-green
coldbox
cctv
mysql-error-1062
mbr
mqx
gdata-api
runas
armcc
viewswitcher
nsmanagedobject
coredump
joyent
horizontal-accordion
imac
xfbml
html-input
visitor-statistic
google-friend-connect
subviews
coda-slider
dmx512
ext3
rescale
firefox4
data-driven
noscript
nerddinner
thread-local-storage
msdev

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App