Java Async in Play 2.0 using Promise

1,133 views
Skip to first unread message

Vladimir Vlach

unread,
Apr 30, 2012, 2:19:12 PM4/30/12
to play-fr...@googlegroups.com
Hi,

I struggle to come up with Asynchronous architecture for my project using Promise using just Java in Play 2.0.

I'd like to fist request data from datastore in parallel - each is time consuming task and wait for all queries to complete:

// runs in serial fashion
public static Result showSomePage() {
  UserObject userObject1 = SlowQuery.getUser(440);
  CategoryObject categoryObject1 = SlowQuery.getCategory("root");

  return ok("some page to render");
}

How can I transform this into parallel execution using Play Async Framework?

This is what I could come up with but it does not wait for the results.

Promise<DataObject> userObject1 = SlowQuery.getUser(440);
Promise<DataObject> userObject2 = SlowQuery.getCategory(420);
async(userObject1.map(new Function<DataObject, Result>() {
public Result apply(DataObject res) {
Logger.debug("Got result (userObject1): " + res.toString());
return ok("Result Received");
}
}));
Logger.debug("finished, yet Result is still not available.");

This execution does not wait for promiseOfResult1 to be completed. I also need the result in main scope. How can I achieve this?

Thanks,
Vlad


Julien Richard-Foy

unread,
Apr 30, 2012, 3:41:14 PM4/30/12
to play-fr...@googlegroups.com
There is a missing “return” keyword before the “async” call:

return async(…);

Now, to transform promises the current way is to use flatMap and map:

return async(userObject1.flatMap(new Function<UserObject, Promise<Result>>() {
@Override
public Promise<Result> apply(UserObject userObject) {
return categoryObject.map(new Function<CategoryObject, Result>() {
@Override
public Result apply(CategoryObject categoryObject) {
return ok("easy, isn’t it?");
}
});
}
}));

Ok, that’s not very readable, but with the upcoming Java 8, the above
code could be written as this:

return async(userObject1.flatMap((UserObject userObject) -> {
categoryObject.map((CategoryObject categoryObject) -> {
ok("easy, isn’t it?");
});
}));

bdeveloper01

unread,
Oct 1, 2012, 8:29:17 AM10/1/12
to play-fr...@googlegroups.com

  Hai!

  This is my controller file


    static boolean checkflag = false;
    static Double dataValue = 0.0;
    static Cancellable timerCall = null;
    static Thread tt;
    static Thread ttt;
    static Promise<Result> promiseOfPIValue1 = null;
 
  public static Result index() {
     
      Promise<Double> promiseOfPIValue = registerListener();
      System.out.println("initial value :"+promiseOfPIValue.get());
      Promise<Result> promiseOfResult = null;
      if(promiseOfPIValue != null)
        {
        promiseOfResult = promiseOfPIValue.map(
          new Function<Double,Result>()
          {
              public Result apply(Double pi) throws Throwable {
              { 
                  System.out.println("PI value computed: " + pi);
                  return ok("PI value computed: " + pi);
              }
              }
          }
          );
        timerCall.cancel();
        checkflag = false;
        }
     
    //return ok(index.render("Your new application is ready."));
    return Results.async(promiseOfResult);
  }

private static Promise<Double> registerListener() {
    // TODO Auto-generated method stub
   
    System.out.println("Listener boolean value :"+checkflag);       
    Promise<Double> pd = Akka.future(
            new Callable<Double>()
            {
                public Double call()
                {
                                   
                    if (checkflag)
                    {
                        dataValue = 3.14;                           
                        return dataValue;
                    }
                    else
                    {
                        dataValue = null;
                        return dataValue;
                    }
                }
            }
    );
   
    if(dataValue == null)
    {
        pd = null;
        System.out.println(Thread.currentThread().hashCode());
       
        //ping();
        timerCall = Akka.system().scheduler().schedule(
                Duration.create(0, TimeUnit.MILLISECONDS),
                Duration.create(10, TimeUnit.SECONDS),
                new Runnable() {
                    public void run()
                    {
                        System.out.println(Thread.currentThread().hashCode());
                        System.out.println("Scheduler is calling ...");
                        if(ping())
                        {
                            index();
                        }
                    }
                });       
    }
    return pd;
}

private static boolean ping() {
    // TODO Auto-generated method stub
    System.out.println("ping boolean value :"+checkflag);
    {   
        if (checkflag)
        {
            timerCall.cancel();               
            return true;
        }
        else
        {
            return false;               
        }           
       
    }
}

public static Result changeValue()
{
    checkflag = true;
    return ok("getit");       
}



-------------------------------------------------


   This is my out :

    PI value computed: null


   when i run this method changeValue();


   PI value computed: 3.14

---------------------------------------------------

  here
    list of return type method.
    1. index ()
    2. registerListener()
    3. ping()
    4. changeValue()


  My index method should not be returned null value ? is it possible? then help me.



 


   
Reply all
Reply to author
Forward
0 new messages