JME
JME

Reputation: 2363

C# delegates to Java and asynchronous handling of methods

I have been tasked with creating Java code with similar functionality to the code below. Currently I am struggling with understanding exactly what the code does and how to simulate the effect in Java.

    #region "Send Aggregate Event"

    /// <summary>
    /// Delegate for async sending the AggregateEvent
    /// </summary>
    /// <param name="request"></param>
    public delegate void SendAggregateEventAsync(AE request);
    SendAggregateEventAsync _sendAggregateEventAsync;

    /// <summary>
    /// IAsyncResult pattern to async send the AggregateEvent
    /// </summary>
    /// <param name="request"></param>
    /// <param name="callback"></param>
    /// <param name="state"></param>
    /// <returns></returns>
    public IAsyncResult BeginSendAggregateEvent(AE request, AsyncCallback callback, Object state)
    {
        _sendAggregateEventAsync = new SendAggregateEventAsync(SendAggregateEvent);
        return _sendAggregateEventAsync.BeginInvoke(request, callback, state);

    }

    public void EndSendAggregateEvent(IAsyncResult result)
    {
        object state = result.AsyncState;
        _sendAggregateEventAsync.EndInvoke(result);
    }

    /// <summary>
    /// Send an aggregate event to the Device Webserver
    /// </summary>
    /// <param name="request">The AggregateEvent request</param>
    public void SendAggregateEvent(AE request)
    {
        if (request == null) throw new ArgumentNullException("request");

        String message = ChangeDatesToUTC(MessageHelper.SerializeObject( typeof(AE), request), new String[] { "EventTime" }, url);
        SendMessage(message);
    }
    #endregion 

There are several other events all with similar code to the provided above. From the comments, I understand that the code is intended to asynchronously handle the SendAggregateEvent method. What I do not understand is why the delegate modifier is used, or how to replicate this type of asynchronous handling in Java.

Also from reading this thread

Java Delegates?

I understand that there is no "easy" way to simulate the delegate functionality in java. Is it necessary to have the delegate functionality to have the SendAggregateEvent method handled asynchronously? If not, can someone suggest how I would do this?

Upvotes: 1

Views: 722

Answers (2)

Tim S.
Tim S.

Reputation: 56556

According to How to asynchronously call a method in Java's answer, FutureTask is a good way in Java to asynchronously run a method. Here's some Java code that runs a task asynchronously (see it run at http://ideone.com/ZtjA5C)

import java.util.*;
import java.lang.*;
import java.util.concurrent.FutureTask;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println("Before");
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        FutureTask<Object> futureTask = new FutureTask<Object>(new Runnable() {
            public void run()
            {
                System.out.println("Hello async world!");
            }
        }, null);
        System.out.println("Defined");
        executorService.execute(futureTask);
        System.out.println("Running");
        while (!futureTask.isDone())
        {
            System.out.println("Task not yet completed.");

            try
            {
                    Thread.sleep(1);
            }
            catch (InterruptedException interruptedException)
            {
            }
        }
        System.out.println("Done");
    }
}

Upvotes: 1

Justin Pihony
Justin Pihony

Reputation: 67115

This is actually the old way of writing async code in C#, commonly referred to as the Async Programming Model

I am not familiar enough with java, but all you really need to replicate this code is to create a method that does the action synchronously SendAggregateEvent and a means to call that asynchronously SendAggregateEventAsync

More specifically to some of your questions. The delegate is only being used to encapsulate the SendAggregateEvent method so that it and its parameters can be invoked on a potentially different thread (keeping in mind that async is not necessarily multi-threaded)

It goes something like this:

var referenceToTaskBeingRun = BeginSomeMethod() 
//the above wraps the actual method and calls it, returning a reference to the task
var results = EndSomeMethod(referenceToTaskBeingRun ); 
//the above sends the reference so that it can be used to get the results from the task. 
//NOTE that this is blocking because you are now waiting for the results, whether they finished or not

The preferred way to do this now is to use the Task Parallel Library, which has a much easier to read code base.

So, all of that being said, the key to focus on this code would be that you just need a method and an async version of that method. The implementation should be up to you and your programming stack. Do not try to force another stack's implementation where it does not belong...especially an implementation that is not even the preferred methodology any longer.

Upvotes: 4

Related Questions