Sunday, June 27, 2010

Invoke code on a certain thread in C# / .NET

Virtually all GUI frameworks and the languages that come with them give you the possibility to invoke a certain piece of code on the UI thread. This is necessary because the UI components aren't usually thread safe (making all their methods thread safe would be a big blow to the performance of the application), so any update of the UI can't be done from another thread. That piece of code needs to be marshalled to the main thread.
.NET goes a step further and offers us the possibility to invoke a piece of code on any thread. The example bellow shows how this can be done.
ThreadTask will be run in a new thread, whose name is "Alpha thread". We create a Control on this thread (new Control()) and then we create its handle: ctrl.CreateControl().
Finally, we do Application.Run(), which makes our thread wait for messages in the message loop.
Then we use our control to invoke the method MyTestMethod on our thread.

Note that control handle creation is essential; without it, MyTestMethod would be invoked on the main thread. Also, attaching the thread to the message loop by doing Application.Run() ensures that the thread waits for invokes from other threads.



using System;
using System.Windows.Forms;
using System.Threading;

namespace TestThreads2 {
    public class TestThread {
        private Control ctrl = null;

        // This method that will be called when the thread
        // is started
        public void ThreadTask() {
            if (ctrl == null) {
                // create the control
                ctrl = new Control();
                // create the handle
                ctrl.CreateControl();
            }
            Console.WriteLine("ThreadTask is running on thread: " +
                Thread.CurrentThread.Name);
            // ensure the message loop is attached to this thread
            Application.Run();
        }

        public Control Ctrl {
            get { return ctrl; }
            set { ctrl = value; }
        }
    }

    public class Program {
        private static void MyTestMethod() {
            Console.WriteLine("TestMethod invoked on thread: " +
                Thread.CurrentThread.Name);
        }

        static void Main(string[] args) {
            //Control.CheckForIllegalCrossThreadCalls = true;
            TestThread myThread = new TestThread();
            Thread thread =
                new Thread(
                    new ThreadStart(myThread.ThreadTask)
                );
            thread.Name = "Alpha thread";
            thread.Start();
            Thread.Sleep(1000);
            if (myThread.Ctrl.InvokeRequired) {
                myThread.Ctrl.BeginInvoke(
                    new MethodInvoker(MyTestMethod)
                );
            } else {
                MyTestMethod();
            }
        }
    }
}




Check out here how to do the same thing in Java.

Saturday, June 19, 2010

Invoke code on a certain thread in Java

I think Java should be a bit jealous on the .NET's interesting feature of being able to invoke a piece of code on any given thread. In .NET that's possible by creating a Control (say myControl) on a certain thread and then using myControl.Invoke or myControl.BeginInvoke having as parameter the piece of code you want to invoke on that thread. The parameter is a delegate, another feature missing in Java, but let's ignore this for now.
In Java we have SwingUtilities.invokeAndWait and SwingUtilities.invokeLater to invoke code on the event dispatching thread, but not on any given thread. They take a Runnable as parameter.

So how would we implement such a feature in Java ? We'll need a thread that has nothing better to do but try to dequeue items from its queue and invoke them (the items would be the pieces of code that we need invoked on that thread). Something like this:

package threading;


import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;


public class Invoker {
    
    private static Thread myThread;
    private static BlockingQueue<Task> queue;
    
    private Invoker() {
    }
    
    public static void BeginInvoke(Task task) {
        if (myThread == null) {
            queue = new LinkedBlockingQueue<Task>();
            myThread = new MyThread(queue);
            myThread.start();
        }
        if (Thread.currentThread() != myThread) {
            try {
                queue.put(task);
            } catch(InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        } else {
            task.perform();
        }
    }


}


And the actual thread (I simulate the .NET delegate by using Java anonymous classes):


package threading;


import java.util.concurrent.BlockingQueue;


public class MyThread extends Thread {
    private final BlockingQueue<Task> taskQueue;
    
    public MyThread(BlockingQueue<Task> queue) {
        taskQueue = queue;
    }
    
    public void run() {
        while(true) {
            try {
                Task currentTask = taskQueue.take();
                currentTask.perform();
            } catch (InterruptedException e) {
                e.printStackTrace();
                // Restore the interrupted status
                Thread.currentThread().interrupt();
            }
        }
    }


}


We need an interface for our task - either an existing one (Swing uses Runnable), or a new one, like:

package threading;


public interface Task {


    void perform();
}


Finally, the test class with the main method:


package threading;


public class Test {


    public static void main(String[] args) {
        System.out.println("main thread: " + Thread.currentThread().getId() + " " + Thread.currentThread().getName());
        Invoker.BeginInvoke(new Task() {
            public void perform() {
                System.out.println("perform task on thread: " + Thread.currentThread().getId() + " " + Thread.currentThread().getName());
                
            }
        });
        Invoker.BeginInvoke(new Task() {
            public void perform() {
                System.out.println("perform task again on thread: " + Thread.currentThread().getId() + " " + Thread.currentThread().getName());
                
            }
        });
    }
}

It should come as no surprise the output:

main thread: 1 main
perform task on thread: 7 Thread-0
perform task again on thread: 7 Thread-0

Monday, June 7, 2010

Mashup with Google Maps or How to Call Java from JavaScript


You can simply embed Java code with the usual notation and even expressions (< % = expression % >) in JavaScript used in JSP.

Below is an example of how to do that. The code creates some Java arrays (between <% and %>) and uses them in Javascript in order to show markers on a Google map. You can see it in action here (choose trip Customizer and play with it).
The code talks for itself, so here it is:

<HEAD>

<title>Customize you trip !</title>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAyBigJTywiIxNM2cWUWhcFxR-sC-25ycSkOaRk1LgFwDltfgq9BRvhFBXWyducVZRhIvJw2DLcsPUdg"
type="text/javascript"></script>
<script type="text/javascript">

//<![CDATA[

function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(45.29, 25.56), 6);
var coords = new Array();

<%
int[] coordsX = (int[])(request.getSession().getAttribute("coordsX"));
int[] coordsY = (int[])(request.getSession().getAttribute("coordsY"));
String[] locations = (String[])(request.getSession().getAttribute("locations"));
if ((coordsX == null) || (coordsX.length == 0)) {
coordsX = new int[1];
coordsX[0] = 0;
coordsY = new int[1];
coordsY[0] = 0;
}
for (int i = 0; i < coordsX.length; i++) {
if (
(coordsY[i] < 2967) &&
(coordsY[i] > 2021) &&
(coordsX[i] < 4823) &&
(coordsX[i] > 4362)
) {
%>
var coord = new GLatLng(
<%= (float)coordsX[i]/100 %>,
<%= (float)coordsY[i]/100 %>);
var marker = new GMarker(coord);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml("<b><%= locations[i] %></b>");
});
map.addOverlay(marker);
coords[<%= i %>] = coord;
<%
}
}
%>
var polyline = new GPolyline(coords, "#ff0000", 10);
map.addOverlay(polyline);


// define the crosshair tile layer and its required functions
var crossLayer = new GTileLayer(new GCopyrightCollection(""), 0, 15);
crossLayer.getTileUrl = function(tile, zoom) {
return "./include/tile_crosshairs.png";
}
crossLayer.isPng = function() {return true;}

// Create a new map type incorporating the tile layer
var layerTerCross = [ G_PHYSICAL_MAP.getTileLayers()[0], crossLayer ];
var mtTerCross = new GMapType(
layerTerCross,
G_PHYSICAL_MAP.getProjection(),
"Ter+");
map.addMapType(G_PHYSICAL_MAP);
map.addMapType(mtTerCross);
map.addControl(new GLargeMapControl())

var mapControl = new GHierarchicalMapTypeControl();
// Set up map type menu relationships
mapControl.clearRelationships();
mapControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", false);
mapControl.addRelationship(G_PHYSICAL_MAP, mtTerCross, "Crosshairs");
// Add control after you've specified the relationships
map.addControl(mapControl);
}
}
//]]>
</script>
</HEAD>

In the code above, "map" is actually a div:



<div id="map" style="width: 700px; height: 400px"></div>



In case you're wondering how this mix of JSP, JavaScript and Java actually works, let's start with the JSP: as we know, JSP runs on the server side and gets translated into a servlet. Thus, the code between < % and % >, including the one inside JavaScript, is textually copied into the servlet code,  since it is just Java code. The resulting servlet will generate HTML, so it will also dynamically generate the JavaScript code (which you can see in your browser by viewing the page source). The generated JavaScript code will have the for loop expanded with actual values for the coordinates and it will execute on the client side, in the browser.
That's all, folks.




Tuesday, June 1, 2010

Hibernate: OpenSessionInView explained


When you enter the Hibernate world, you hear a lot about sessions, transactions, session-per-request, etc., to the point you start mixing the concepts. Let's face it:
Fact 1: Hibernate is big
Fact 2: Hibernate is easy if you understand the fundamentals; everything else builds on top of those
I'll try to explain these fundamental concepts and then I'll cover the famous OpenSessionInView pattern with an example.

So, what's a session ? If I tell you "a session is a unit of work bla bla bla", you'll say "I've read that in about 1,200,000 hits returned by Google and yet I don't really understand the concept". Let me put it this way: from the developer's perspective (what can I do, I usually incarnate this perspective), a session is actually an API that abstracts the notion of persistence service. Thus, whenever you want to do something with the objects (representing the O in the ORM), like synchronize them with the DB, persist them to the DB, etc., you need a session instance.

However, as we all know, each operation to the DB - be it a read or a write - needs a transaction. Thus, because you use the session in order to perform DB operations, it means whenever we're using the session we need a transaction (with a noteworthy exception, but we'll cover that later). If you're trying to run an operation on the session without being inside a transaction, you'll get a runtime exception of the type org.hibernate.TransactionException: Transaction not successfully started.
In other words, it's quite logical that the scope of a session (i.e. from the moment you create/open it to the moment you close it) and the scope of a transaction coincide. Without further ado, this is the session-per-request pattern.

Now let's take a painfully real example. Suppose I have two tables in my DB: a Patients table and a PatientPhones table (basically each patient from the first table has a number of telephone numbers recorded in the second table). They are linked by PATIENT_ID, a foreign key in PatientPhones table and primary key in the Patients table.
The Hibernate file that describes these tables is:


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="model">
<class name="Patient2" table="PATIENTS">
<id name="id" column="PATIENT_ID">
<generator class="assigned" />
</id>
<property name="name"/>
<property name="sex"/>
<property name="birth_day"/>
<property name="birth_month"/>
<property name="birth_year"/>
<property name="address"/>
<property name="cnp"/>

<bag name="phoneNumbers" table="PATIENT_PHONES" cascade="all" lazy="true">
<key column="PATIENT_ID"/>
<element type="string" column="PHONE_NUMBER"/>
</bag>
</class>

</hibernate-mapping>

Notice the lazy="true" attribute above ? This means that actually the phone numbers will be retrieved from the DB lazily, i.e. when we request them. For example, suppose I do this:








Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();

// note that in this query we use the name of the class, Patient2,
// rather than the name of the table (Patients)
ArrayList patients =
new ArrayList(session.createQuery("from Patient2").list());
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
Then, after the session has been closed, I do this:








for (Patient2 p : patients) {
System.out.println("Patient " + p.getName() + " " + p.getId());
}
This will work, because the patients list has been eagerly populated with the DB data inside the transaction above.
But if I try:




for (Patient2 p : patients) {
  if ((p.getPhoneNumbers() != null) && (p.getPhoneNumbers().size() > 0)) {
    System.out.print(" * phones :");
    Iterator iter = p.getPhoneNumbers().iterator();
    while (iter.hasNext()) {
        System.out.print(" " + iter.next());
    }
    System.out.println();
  }
}
This fails with the error LazyInitializationException (or something like this) because in the xml file above I asked the phone numbers to be lazily retrieved, i.e. when I do p.getPhoneNumbers(). However, at this moment I am outside the session, so I'm working with the detached object p. In order to be able to retrieve the phones, I have 2 choices:
1. either do lazy = "false" in the xml above
2. or reattach each object p to which I'm asking getPhoneNumbers(), like this:




Session session = HibernateUtil.getSessionFactory().getCurrentSession(); 
session.beginTransaction(); 
for (Patient2 p : patients) {     
 System.out.println("Patient " + p.getName() + " " + p.getId());     
 session.lock(p, LockMode.NONE);     
 if ((p.getPhoneNumbers() != null) && (p.getPhoneNumbers().size() > 0)) {         
  System.out.print(" * phones :");         
  Iterator iter = p.getPhoneNumbers().iterator();         
  while (iter.hasNext()) {             
   System.out.print(" " + iter.next());         
  }         
  System.out.println();     
 } 
} 
session.getTransaction().commit(); 
HibernateUtil.getSessionFactory().close();  
This situation is extremely relevant, because in a typical web application you'd do exactly this:
whenever you show the results of a DB query (via Hibernate) in your view (a jsp page for example), your objects are detached (the session is closed, the transaction committed), so you can get the exception LazyInitializationException.
The solution is the Open Session in View pattern, which simply states that the session should remain open and the transaction uncommitted until the results have been processed in the view. This can be easily done with a filter, e.g.:





public class HibernateSessionRequestFilter implements Filter {

private SessionFactory sf;

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {

try {

sf.getCurrentSession().beginTransaction();
// Call the next filter (continue request processing)
chain.doFilter(request, response);
 // Commit and cleanup
 sf.getCurrentSession().getTransaction().commit();
} catch (StaleObjectStateException staleEx) {
 throw staleEx;
} catch (Throwable ex) {
 // Rollback only
 try {
  if (sf.getCurrentSession().getTransaction().isActive()) {
  sf.getCurrentSession().getTransaction().rollback();
  }
 } catch (Throwable rbEx) {
  }
  // Let others handle it... maybe another interceptor for exceptions?
  throw new ServletException(ex);
}
}

public void init(FilterConfig filterConfig) throws ServletException {
sf = HibernateSession.getSessionFactory();
}
(NOTE: this pattern only works when the jsp and Hibernate code run on the same JVM, i.e. when the presentation and business logic tiers run on the same machine)


I will register this filter in my web.xml:


<filter>
<filter-name>HibernateFilter</filter-name>
<filter-class>view.backing.HibernateSessionRequestFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>HibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Now, in one of my JSF backing beans, PatientsSearch.java, I could have:




public void getAllPatients() {
Session session = null;
try {
 session = HibernateSession.getSessionFactory().getCurrentSession();
 Query query = session.createQuery("from Patient2 p order by p.name asc");
 int pageNumber = 1;
 int pageSize = rowsPerPage;
 query.setFirstResult((pageNumber - 1) * pageSize);
 query.setMaxResults(pageSize);
 patients = new ArrayList(query.list());
 totalRows = count();
} catch (Exception e) {
 if (session != null) session.getTransaction().rollback();
 e.printStackTrace();
}
}

And in the view, patientSearch.jsp, I could have:







<h:dataTable value="#{PatientsSearch.patients}" var="patient"


binding="#{PatientsSearch.dataTable1}" id="dataTable1"
border="2" bgcolor="White" frame="border"
">
<h:column>
<f:facet name="header">
<h:outputText value="Name"/>
</f:facet>
<h:commandLink action="#{PatientsSearch.edit}">
<h:outputText value="#{patient.name}" style="font-family:Garamond;"/>
</h:commandLink>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="ID"/>
</f:facet>
<h:outputText value="#{patient.id}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Address"/>
</f:facet>
<h:outputText value="#{patient.address}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Fix phone"/>
</f:facet>
<h:outputText value="#{patient.phoneFix}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Mobile phone"/>
</f:facet>
<h:outputText value="#{patient.phoneMobile}"/>
</h:column>
</h:dataTable>

<h:commandButton value="All patients" id="commandButton1"
action="#{PatientsSearch.getAllPatients}"/>


This works just as described above: in the view I don't need to worry about the session; even if lazy = "true", I know that the calls patient.phoneMobile and patient.phoneFix will retrieve the data, because everything happens between the two important statements in the filter:







sf.getCurrentSession().beginTransaction();
....
sf.getCurrentSession().getTransaction().commit();


By the way, in Patient2.java, I have:

public String getPhoneFix() {

    if (phoneNumbers.size() > 0) return (String)phoneNumbers.get(0);

return null;

}

Simple, isn't it ?


However, there is potentially something wrong with this approach. Check out the next article to see what and how we can correct it.


So, what's your story ?


First time when I landed into the world of IT, I felt .... how should I put it ? A bit like E.T. (Remember the movie ?)
I guess what I mean is that I've always had a complex regarding IT. Somehow, when I first started I had an uneasy feeling, since it was not a hobby for me, as I saw it was at some of my high-school colleagues and later at the university. They were thinking computers, dreaming computers, breathing computers .... Moreover, all those who loved IT also liked science-fiction movies. I hated them (I mean the movies; well, except some really good ones, like E.T.). I liked totally different things and the distance between me and my IT loving colleagues was like from here to Mars.
It made me think. Was it actually good for me ? After all, I chose IT. Probably because I couldn't do anything else ....
It took me several years to understand IT: anybody can do IT. All you need is to enjoy it a bit. In order to enjoy it, you have to understand it. So, to make a long story short, I'm building this blog to demystify IT. In other words, to explain IT first of all to myself and to whoever feels like me.
This blog will contain random topics about programming languages and software engineering techniques. The kind of things I typically wanted to know but was afraid to ask. So I had to discover them in a tough, but fascinating journey.