Since Appengine won't allow java multithreading, how then can we migrate our existing multithreaded code to the platform?
For example I have the following code:
Thread t = new Thread() {
public boolean alive = true;
public void run() {
while (alive) {
try {
Thread.sleep(5000);
getNewNotifications();
} catch (InterruptedException e) {
// Do nothing
} catch (IOException e) {
}
}
}
};
t.start()
The function getNewNotification() does some several Rest/HTTP calls, that may include some other process that may return indefinitely. I have read the Task Queue
is the solution, however how do we convert this simple code into App engine-friendly code?
How is the code above implemented using Task queue? For example to call getNewNotifications()
for every five seconds.
And that function will get some results from the server, parse the result and then execute the activities/work it needs to do based on the result.
You can create threads in java appengine.
ThreadManager.createThreadForCurrentRequest(new Runnable(){...});
See https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/ThreadManager
A frontend thread will be interrupted and killed when the request is complete, but a spawned backend thread can run for as long as it pleases. Also, try to do more than nothing when you catch InterruptedException; swallowing this exception can cause instances to stay online and will cost you more money.
If you want to make your code work with Runnable and task queues, just implement both Runnable and DeferredTask; both interfaces have the same method signature. To dispatch a deferred task, just do QueueFactory.getQueue("queueName").add( TaskOptions.Builder.withPayload(YourDeferredTask));
You might also be interested in backends. Backends can run as background threads (experimental feature) so they can be used to poll like you are used to do. However if possible it probably is more efficient to use tasks. If the notifications are coming from some other part of your app you could create tasks directly instead of creating notifications.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With