Asynchronous Methods

Introduction

An asynchronous method runs in its own thread and (in its simplest form) once called does not need to wait at any stage for other code to complete. In the conversion of RemObject's Oxygene for .Net demonstration of asynchronous methods to Oxygene for Java, we needed to make several changes. Following the example in a contribution to the RemObjects Talk forum, we added a reference to the rtl jar file.

Adding a Reference

To add a reference in Visual Studio, right click on References in the Solution Explorer:

Adding a reference

Adding a reference

Select the reference by clicking first on the required filename to highlight it then in the box to the left of its name:

Selecting a reference

Selecting a reference

Click the OK button at the bottom of the dialogue box to add the selected reference.

Here is the relevant section of the AsyncMethodsDemo.oxygene project file after the addition:

<ItemGroup>
  <Reference Include="com.remobjects.oxygene.rtl.jar">
     <HintPath>C:\Program Files\RemObjects Software\Oxygene\Cooper\Oxygene Reference Archives\com.remobjects.oxygene.rtl.jar</HintPath>
     <Private>True</Private>
   </Reference>
   <Reference Include="rt.jar" />
</ItemGroup>

The result of making the reference private is that the added jar file is copied to the same directory as AsyncMethodsDemo.jar.

The jar file obtained from code below gave this screenshot when executed.

Output from demonstration

Output from demonstration

Code of AsyncMethodsDemo.pas

namespace async_methods_demo;

interface

type
  ConsoleApp = class
  public
    class method Main;
    method Test(aIdentifier: Integer);
  end;

implementation

class method ConsoleApp.Main;
begin
  writeLn(#13#10'Async method example');
  with lMyConsoleApp := new ConsoleApp() do 
    begin
      async lMyConsoleApp.Test(1);
      async lMyConsoleApp.Test(2);
      async lMyConsoleApp.Test(3);
      async lMyConsoleApp.Test(4);
      { This code will be executed BEFORE all the Test methods have completed their execution. }
      writeLn('All 4 threads have been spawned!');
      System.in.read;
    end;
end;

method ConsoleApp.Test(aIdentifier: Integer); 
begin
  for i: Integer := 0 to 4 do 
    begin
      writeLn('Thread '+ aIdentifier.toString + ': ' + i.toString);
      Thread.sleep(100);
    end;
  writeLn('Thread ' + aIdentifier.toString + ' is done.');
end;

end.

Using a Loop

The following code gave a satisfactory demonstration of the running of asynchronous methods.

for i : Integer := 1 to 4 do
  begin
    async lmyconsoleapp.test(i);
    thread.sleep(5);
  end;    

Without the delay, the Integer 5 is passed to all of the methods. Great care is needed!

Programming - a skill for life!

Language features such as loops, generics, class contracts, asynchronous methods, futures and Sugar in Oxygene for Java