Isolates: how to work with multithreading in Dart

Here we are again with another topic about Dart language, first of all I’d like to start this article with an off-topic.

I joined to FluentJS in San Francisco few weeks ago, an event organize by O’Reilly focus on Javascript development, and I saw a Dart language session, the most amazing thing I’ve seen was the passion behind this project, trust me that it’s not easy today find people that believe in that way in something, Seth Ladd, the speaker and team member of Dart, gave us a great technical introduction to Dart but gave us something more, he transmitted us all his passion on Dart, really amazing!

After this quick off-topic, let’s go ahead with Isolates tutorial.

First of all, Isolates is the Dart way to work with threads and allow to take advantage of your multicore computer, but what is multithreading and when we should use it.

Multithreading

This is a good definition for me: “Multithreading is the ability of a CPU to execute several threads of execution apparently at the same time. CPUs are very fast at executing instructions. Modern PCs can execute nearly a billion instructions every second. Instead of running the same program for one second, the CPU will run one program for perhaps a few hundred microseconds then switch to another and run it for a short while and so on.” (source: cplus.about.com)

And when should we use threads?!

Basically every time you need to speed up an intensive process, for example when you have an heavy process like unzip of a big file or a for cycle with a lots of elements, you should use the threads to don’t freeze the main one and allow your user to work the interface without any issues.

Dart adds this capability in 2 different ways because, as you know you, it can export a project for Dart VM or in Javascript, with Dartium we can use the power of CPUs of your multicore computer and create different threads in each CPU where will be executed your code, in Javascript, Dart converts Isolates in web workers.

Before starting with code I decide to show in a chart how we’ll work with isolates, so basically first of all we create 2 isolates launched from the main isolate and then we pass the final informations elaborated in different isolates to the main one.

Isolates Schema

Last note, when you work with isolate you can have a sender and a receiver, so in the main isolate (launched by the application) you have a port object where you can listen when you receive informations from other isolates and you can pass the sendport object where you can send message to other isolates.

port.receive((data, SendPort replyTo){
replyTo.send("something");
});

Another important thing to remember when you work with isolates, if you need to receive messages from other isolates, is that you always set  the receiver in the main isolate, or you will n0t receive any message from other isolates because the execution of your program is not waiting for any reply without a receiver set.

I created a small project around this topic to show the powerful of the isolates, take a look here:

As you can see when I click on MONO link my CSS animation stops until to the heavy iteration is finished instead when I click on ISOLATE  link everything works well because all the iterations are accomplished in different isolates so the main one could go ahead with own job.

When you want to launch an isolate you have to call the spawnfunction method and pass the main isolate sender:

var isolate = spawnFunction(bigForCycle);
isolate.send("data", port.toSendPort());

After that you can operate with your isolate in this way for example:

void bigForCycle(){
 
 port.receive((data, SendPort replyTo){
 var count;
 for(var i = 0; i < FINAL_AMOUNT; i++){
   count = i;
 }
 replyTo.send(count);
});

}

It’s finally important remember to close isolates after received the message so when they have finished to accomplish own function, to do that you have only to call the close method in the main isolate and it will not receive any other information from other isolates.
In my example I launched 2 isolates to accomplish the task, so I created a counter variables to store how many reply the main isolate received, after received all replies I can close the communication with other isolates:

port.receive((data, SendPort replyTo){
 
 counterIsolate++;
 end = new DateTime.now();
 
 if(counterIsolate == 2){
 var finalTime = end.difference(start).toString();
 myH1.appendHtml("isolate total time: <b>$finalTime</b><br/>");
 // if you want to close isolates you have to use the line below
 port.close();
 
 }

 });

The most interesting thing is that you can accomplish the same task in 2 different way, the first one, as I did in my example, with inline isolates and the second one is loading code dinamically from external Dart files.
To take a look to the second one I suggest to read this post made by Seth Ladd.

Isolate technique is very useful also when you are working on a serverside project with Dart because it could optimize some intensive process that you have to achieve during your project.

I’ve just opened a github repository with all Dart examples that I’m working on, so feel free to check out at this link.
Enjoy!

Advertisement

Dart: elements iteration and CSS manipulation

In my exploration of Dart I’m trying to work in some easy examples that could help me to understand how to accomplish some tasks with this technology.
In this example I tried to understand better how iteration of elements works in Dart, how to create a layout with custom elements (more or less the same topic of a custom item renderer in Flex for example) and finally how to create some animations with CSS3 at runtime.

To accomplish those topics I decided to create a responsive image gallery that works on smartphone, tablet and web too.

image gallery with dart

Responsive image gallery

Iteration

Dart gives few opportunities to iterate trough elements:

  • with Dart language (a classic for cycle)
  • with an HTML template
  • with elements composed by an HTML template and some dart code to cover the business logic of the final element

I jump directly to the second and third method, the first one is quite easy for any developer 😉
In my sample I decide to use a simple HTML template, so basically you can define inside your html a tag <template/> that will allow you to repeat the HTML inside this tag associating it to a list for example, I give you a quick sample:

 <div id="imageCont" class="wrap">
      <template iterate="data in results">
        <div class="image">
          <img id="img_{{data[0]}}" class="faded" src={{data[1]}} width="320" height="240" on-click="onClick($event)" on-mouse-out="onOut($event)" on-mouse-over="onOver($event)" on-load="fadeIn($event)"/>
          <img id="zoom_{{data[0]}}" src="images/zoom.png" class="zoom"/>
          <h2><span>{{data[2]}}</span></h2>
         </div>
      </template>
    </div>

First of all take a look on how I can iterate this part of code; I add a simple iterate attribute associated to a list object (called results in my example) added in my dart file as a public variable.
The list could be a plain list or a list of objects, in this last case you can create multiple iteration item inside the template cycling trough your objects in the same way you have just seen.
I can substitute my data variable with any other name and I don’t need to define in my dart file, as you can see I can also define some variables inside the template getting values from my list object with this syntax: {{data[0]}} (or {{data[“value”]}} it’s the same, depends how you have create the list object).
If you need, you can also made your source variables bindable and any time you’ll change the values of your list, also the view will change the number of elements or the values showed in the HTML page.

Finally when you need to create an iterable object with a complex business logic and you want to separate from the original HTML file you can do that creating a Web Components, but in this case I suggest you to take a look to the Dart language guide that explain very well how to achieve this topic.

Modifying CSS with Dart

Another interesting topic is how to change, add or remove css styles to my DOM objects.
In Dart is so easy like any other javascript library, so basically any DOM element in Dart has a property called “classes” with its associated method add and remove, so when you want to change your CSS class with another one, you have, if you have any classes already associated to the element, remove the old class and then add the new one:

var myDomObj = query("#idObject");
myDomObj.classes.remove("class-to-remove");
myDomObj.classes.add("class-to-add");

You can also style any single property directly with “style” property and set them directly in this easy way:

var myDomObj = query("#idObject");
myDomObj.style
             ..color = "0xFFF"
             ..fontSize = "15px";

As you can see working with CSS in Dart is relative simple, if you want to take a look to the whole project feel free to download it.

Another cool thing that is so useful when you work with mobile apps or websites is to test quickly and frequently your content on the devices, so with DartIDE (you can find it downloading Dart SDK) you can easily test your content trough a web server that starts any time you are testing your app into the browser.
It’s so interesting because you save a lot of time in this way!

I’m trying to figure out right now an hypothetical workflow to create web app, web sites or any other thing with Dart and HTML5.
I believe that use Dart in combination with Edge Reflow could be the best way to create responsive application for any kind of devices, but we have to wait until the release of Edge Reflow (17th June) to know if my supposition is true or not.
When it’ll be released and I’ve few time to invest, I’ll prepare another tutorial around this workflow.
In the meanwhile I hope you are enjoying those experiments with Dart and if you are interesting in any kind of topics on Dart feel free to suggest trough a comment in this post or sending an email

First approach to Dart

Dart Logo

After saw what’s happend during the Google I/O, I decide to make some experiments with Dart.
If you don’t know what is Dart I explain in a while: Dart is a new language that allow to structure  your code in OOP manner with strong typing but with a lot of flexibility.
It’s so similar to Javascript but give you the opportunities to create classes, libraries, isolates (a good implementation to use shared-memory threads) and so on.
For an Actionscript developer, Dart seems to be the natural evolution to Javascript, during last week, also, Adobe announced an extension for Flash that allow to export Flash animations directly to Dart, so another good point on why choice this great new language.
Starting to work with Dart is very very simple, you have only to download Dart from the website and you will find inside the zip the DartEditor, an editor based on Eclipse that will become your new IDE to write Dart application.
When you are working with Dart to create the UI of your project, you can use HTML and CSS and if you have some Javascript library to integrate with Dart, you can do that!!!
With Dart you can decide to create a client or server side project, you can also export your client project for chromium or Javascript, so it’s very flexible and powerful as you can see.
I will not explain how to install Dart and getting started with it because in the official website the “get started” section is well documented, so I prefer to start with an example of a video player, if it’s your first approach to Dart I suggest to take a look, before go ahead with this post, to that section on the official website.

For the UI part of my example I’ve used Topcoat and Dart for the business logic of my video player.
Topcoat is a new Adobe UI library dedicated to style in a good and fast way the main components in a web or mobile application, if you have worked with Flex is more or less the same concept of a theme, so when you don’t want to waste your time creating a custom UI you can easily use Topcoat for your prototypes or example.

Beginning from the UI side, after created a new Dart project, I create an HTML file where I add a title, an instance of video component, and a div with some buttons and a slider to manage the volume:

<div class="centerClass">
      <h1>VideoPlayer made with DartJS</h1>
      <video id="video" width="640" height="420"/> 
    </div>
    
    <div class="centerClass">
      <a id="playBtn" class="light-button">Play</a>
      <a id="resumeBtn" class="light-button">Restart</a>
      <span id="currTime">00:00/00:00</span>
      <span><input id="volume" type="range" class="dark-slider" value="100"/></span>
    </div>

After that I created my class in the DartEditor, all Dart classes have the extension .dart.
At the beginning of this class I’ve retrieve the id of my components inside the HTML file with query method, as you can see below, it allows me to work with them directly from my Dart class:

volumeSlider = query("#volume");
  currTimeDisplay = query("#currTime");
  player = query("#video");
  playBtn = query("#playBtn");
  restartBtn = query("#resumeBtn");

Then I loaded my mp4 file inside the video component and I’ve added all listeners that I need to intercept events from user or from the video instance:

player.src = "video/test.mp4";

//player listeners
  player.onLoadStart.listen(checkLoading);
  player.onEnded.listen(restartVideo);
  player.onTimeUpdate.listen(refreshData);
  
  // buttons listeners
  volumeSlider.onChange.listen(setVolume);
  restartBtn.onClick.listen(restartVideo);
  playBtn.onClick.listen(playVideo);

After that I’ve only to add the business logic for any interaction and everything will be done:

void refreshData(event){
  currTimeDisplay.text = returnDisplayTime(player.currentTime) + "/" + returnDisplayTime(player.duration);
}
 
void checkLoading(event){
  //after video si loaded I play it
  player.play();
  isWorking = true;
  playBtn.text = "Pause";
}
 
void playVideo(MouseEvent event){
  //managing if I've to play or pause the video
  if(isWorking){
    isWorking = false;
    player.pause();
    playBtn.text = "Play";    
  } else {    
    isWorking = true;
    player.play();
    playBtn.text = "Pause";
  }
}
 
void setVolume(event){
  //setting volume video value (from 0 to 1)
  player.volume = int.parse(volumeSlider.value)/100;
}
 
void restartVideo(event){
  player.load();
  player.play(); 
}

When you have finished you can easily export your project to Javascript from the DartEditor menu (Tools > Generate Javascript) and publish on your website.
Finally this is the link to download the entire project.

As you can see Dart is not a complex language in particular if you have a solid understanding of OOP language, I personally think that many Actionscript developers will be find in Dart a good approach to Javascript and probably new stimulus on create new engaging experiences.

Playing with Google+ API and Actionscript 3

Yesterday I saw that Google has released Google+ API, so I started to played with in my favorite part of the day: the night!

For now Google has published only public APIs that allow you to retrieve user’s informations and his activities list, all API are made in RESTful and JSON that are so easy to add in your project.
When Google will release next APIs, I hope soon, you can consume them with an oAuth 2.0 authentication, like Facebook.
I made a simple example to retrieve data from my Google+ profile in Actionscript for Android, you can download the source files directly from here.

If you want to play with Google+ API, first of all you have to request your Google+ API key; to do that go to Google API console and activate Google+ service, then in the details page you can find your key.

Google+ RESTful services get us a JSON response, to read it in your Flash/Flex application remember that you need as3corelib that have the JSON deserializer, for example you can push in a generic Object all data retrieved from Google+ service or if you prefer you could create a Value Object that it could be more useful.
In this case I decode directly in a generic Object, like you can see in this code snippet:

var data:Object= JSON.decode(dataToRead, true);

then now you can easily access to informations:

var icon:String = data.image.url;
var name:String = data.displayName;
var tagline:String = data.tagline;
var description:String = data.aboutMe;

Another easy feature that you can add in your Google+ application is a static image of the map, like in your web page, using Google Maps Static API.
You can easily make a query to Google Maps passing in GET params like: the dimension of image, the location and the zoom; you can also add more params that you find in the docs of Google Maps Static API.
Here a code sample to add this feature in your Flash application, in those line I request for an image with width 480px, height 200px, with roadmap skin and with a zoom of 15x:

var mapLoader:Loader = new Loader();
//city is a variable with the name of the place that you have to retrieve.
mapLoader.load(new URLRequest("http://maps.googleapis.com/maps/api/staticmap?center="
+city+"&zoom=15&size=480x200&maptype=roadmap&sensor=true"));
mapLoader.y = this.stage.stageHeight - 200;
addChild(mapLoader);

Like you can see work with those APIs are pretty easy, so now we have to wait for final release and then we can start to create our Google+ integration with the Flash Platform.