wiradikusuma
wiradikusuma

Reputation: 1909

Objectify doesn't work inside createThreadForCurrentRequest()

This is a follow-up question to an answer here.

I have the following code in a servlet:

createThreadForCurrentRequest(() => {
    // do stuff
}).start();

But when I run it locally, I received this exception:

Exception in thread "Thread-17" java.lang.IllegalStateException: You have not started an Objectify context. You are probably missing the ObjectifyFilter. If you are not running in the context of an http request, see the ObjectifyService.run() method.

Where do I do wrong?

To paraphrase: How do I run Objectify inside thread spawned by createThreadForCurrentRequest()?

EDIT 1: By request, here's the web.xml:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         metadata-complete="true">

    <absolute-ordering/>

    <!-- Register Objectify model -->
    <listener>
        <listener-class>foo.ObjectifyListener</listener-class>
    </listener>

    <filter>
        <filter-name>objectify</filter-name>
        <filter-class>com.googlecode.objectify.ObjectifyFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>objectify</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>bar</servlet-name>
        <servlet-class>foo.BarServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>bar</servlet-name>
        <url-pattern>/foo/bar/</url-pattern>
    </servlet-mapping>

</web-app>

EDIT 2:

I use the new (currently in beta) Java 8 runtime.

Upvotes: 0

Views: 292

Answers (1)

stickfigure
stickfigure

Reputation: 13556

You can create a unit of work (exactly the same way the filter does) like this:

ObjectifyService.run(() -> {
    ofy().load()...etc
});

Also see the begin() method, which is pretty much the same thing (you can use try-with-resources instead of passing a closure).

Upvotes: 1

Related Questions