Monday, December 23, 2013

Using the executorservice to create new Threads on google appengine

Appengine actually allows you to spawn new threads, as long as you follow the rules defined in the docs. Here is how I did it,
package no.nilsapp.someapp.cronjobs;
import com.google.appengine.api.ThreadManager;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
public class AppengineExecutor {
public void run() throws IOException {
ThreadFactory factory = ThreadManager.currentRequestThreadFactory();
ExecutorService executor = Executors.newCachedThreadPool(factory);
List<Shipment> shipmentsToCheck = dataStorage.getShipmentsNotDelivered();
System.out.println("Checking shipments " + shipmentsToCheck.size());
for (Shipment shipment : shipmentsToCheck) {
// please note that "MyRunnable" implements Runnable and cannot directly extend Thread.
Runnable checkShipmentTask = ThreadManager.createThreadForCurrentRequest(new MyRunnable(shipment));
executor.execute(checkShipmentTask);
}
System.out.println("Sent all jobs to execution.");
executor.shutdown();
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
copy, paste and use it as you wish.