Calling Objectify within DeferredTask

This article explains how to call Objectify within a DeferredTask on Google App Engine push queue.

This article appeared first on

Objectify Wiki presents a clear explanation how to user ObjectifyFilter to get or inject a Objectify instance into your servlet. However there is no word using Objectify within push queues.

Solution 1: Create task with worker URLs that are mapped to your servlet

Let ObjectifyFilter inject the Objectify instance. It your responsibility to encode and handle parameters and to secure your URLs.

Solution 2: Create a DeferredTask

Let GAE handle parameters and security for you. Call ObjectifyService.begin() to manually start an Objectify session. Close this session manually when the task finishes. A try-with-resources block handles everything for you.

import com.googlecode.objectify.ObjectifyService;

public class MyTask implements DeferredTask {
   final String parameter;
   public MyTask(String parameter) {
      this.parameter = parameter;

   public void run() {
      try (Closeable closeable = ObjectifyService.begin()) {
          Objectify ofy = MyObjectifyService.ofy();          
          // start transactions, read or write data.
          // ...
      } catch (IOException | RuntimeException e) {
          // log or handle failure.

I recommend a class that statically registers your entities before calling any Objectify method.

public class MyObjectifyService {
   static {
      // ...
   public static Objectify ofy() {
      return ObjectifyService.ofy();


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: