Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreading with Appengine

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.

like image 651
quarks Avatar asked Dec 28 '22 01:12

quarks


2 Answers

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));

like image 104
Ajax Avatar answered Dec 29 '22 15:12

Ajax


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.

like image 41
Eelke Avatar answered Dec 29 '22 14:12

Eelke