I am developing a system where the server needs to send (every second) values to multiple clients. My idea was to implement a single Thread for each client to do this. I implemented the Threads in the following Fashion:
Runnable tu = new TimeUpdater(market_id);
Thread thread = ThreadManager.createBackgroundThread(tu);
thread.start();
and
public class TimeUpdater implements Runnable{
boolean close = false;
..
public void run() {
while(!close){
try {
//do something
Thread.sleep(1000);
}catch (InterruptedException e) {
}
}
}
}
To pause the Threads i just use:
thread.interrupt();
thread = null;
But i just can’t make the pause / resume of the threads work.
Does anyone have a better idea to use multithreading with GWT on the server?
Edited original post by mistake. – Martin
First, your background threads require these processes to be running on the backend. In order to do this, you must send a task to the backend, where you will already be in a running task, so adding threads is just more latency to your app. You do not actually need threads to dispatch messages; backend requests last for 10 minutes. Also, your threads will be running in their own request; you may be able to store a list of threads in static ram to be able to access them, but a better solution is distribute messages as they come in, rather than keep instances online and sleeping. If your clients send messages to the server every second, that rpc can just key-query which other users need to be notified, and send the messages immediately. If you use asynchronous datastore processes, it will be very fast. Also, if you want to cut request times, you can have the rpc start the message sends, then have the servlet return response, and then finalize the asynchronous requests after the reply is already going down the wire.
I do post-processing like this using a ThreadLocal map and a cleanup filter. Servlets post jobs to a list of runnables, and the cleanup filter runs the jobs. So long as you start your async requests immediately, they are often done by the time the cleanup filter gets to them.
https://developers.google.com/appengine/docs/java/datastore/async