Thursday, February 28, 2013

Flushing with a volatile!

Core Java provides different ways of ensuring visibility of actions on memory performed by one thread to other threads. You probably can think of synchronization, marking a variable volatile or using a thread safe collection from java.util.concurrent package.

Today we will explore another, less obvious approach. We will use a volatile variable to ensure visibility of another non-volatile variable. Lets start with a simple but flawed example:
class BadTask implements Runnable {
 boolean keepRunning = true;
 
 @Override
 public void run() {
  while(keepRunning) {
  }
  System.out.println("Done.");
 }
}

public class VolatileExp {
 public static void main(String[] args) throws InterruptedException {
  BadTask r = new BadTask();
  new Thread(r).start();
  Thread.sleep(1000);
  r.keepRunning = false;
  System.out.println("keepRunning is false");
 }
}
The intention of this code is to let BadTask run for 1 second and after that to stop it by setting keepRunning boolean to false. As simple as it may look this code is doomed to fail - the BadTask won’t stop after 1 second and will run until you terminate the program manually. If it works fine in your environment try a different one. In my case the above code fails constantly on the following:
$ cat /proc/cpuinfo | egrep "core id|physical id" | tr -d "\n" | sed s/physical/\\nphysical/g | grep -v ^$ | sort | uniq | wc -l
12
$ java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02, mixed mode)
$ cat /proc/version
Linux version 2.6.32-33-server (buildd@allspice) (gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5) ) #72-Ubuntu SMP Fri Jul 29 21:21:55 UTC 2011
If the program does not stop you may wonder what happend. In short - the main thread and the thread running BadTask have been executed on different cores. Each core has its own set of registers and caches. The new value of keepRunning has been written to one of these without being flushed to the main memory. Thus it is not visible to the code running on a different core.

Ok, how we can fix it? The simplest and the most correct way is to mark this variable volatile. Another approach would be to acquire a common lock when accessing it but that would be definetly an overkill.

So what we will do today? We will introduce another variable marked with a volatile keyword! In the above code it does not make much sense and is only for demonstrating some aspects of Java memory model. But think about a scenario where there are more variables of keepRunning nature. Have a look at the below code that does not have visibility problem anymore:
class BadTask implements Runnable {
        boolean keepRunning = true;
        volatile boolean flush = true;

        @Override
        public void run() {
                while(keepRunning) {
                        if(flush);
                }
                System.out.println("BadTask is done.");
        }
}

public class VolatileExp extends Thread {

        public static void main(String[] args) throws InterruptedException {
                BadTask r = new BadTask();
                new Thread(r).start();
                Thread.sleep(1000);
                r.keepRunning = false;
                r.flush = false;
                System.out.println("keepRunning is false");
        }
}
So as already mentioned we have introduced a new volatile variable “flush”. We do two things with it. First, we do a write operation in the main thread, right after modifying a non-volatile keepRunning variable. Second, in the thread running BadTask, we do a read operation on it.
Now, how come the value of keepRunning is flushed to the main memory? This is guaranteded by the current Java memory model. According to JSR133 “writing to a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire”. Thus, actions on memory done by one thread before writing to a volatile variable will be visible to another thread after reading that variable.

This is an advanced technique which should be used sparingly only when the performance has the highest priority. If you are looking for a real life adaptation of it, you can have a look at the ConcurrentHashMap from java.util.concurrent package.

Saturday, January 28, 2012

Proxy and Adapter design patterns.

Recently, when speaking to some of my colleagues, I have noticed a lot of confusion between these two design patterns. Thus, today I'm going to clarify all the doubts :).

First off, both Proxy and Adapter belong to the same group of design patterns – structural one. What are structural design patterns? In simple words, they are patterns that describe ways of combining different entities with each other and thus forming larger structures.

And now a definition from Wikipedia:

“Structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.”

Right. First we will scrutinize the adapter pattern. In a nutshell, it transforms an interface of one class into the interface that is expected. It enables two classes to work together even though their interfaces are not compatible with each other. There are two basic variations of the adapter design pattern: class adapter and object adapter.

  • Class adapter.

In this case, the adapter's class subclasses the class we want to adapt and in the same time it implements the desired interface that the client expects. When the call is made, appropriate inherited methods are being invoked.

  • Object adapter.

On the other hand, in the object adapter, the adapter's class does not subclass the adaptee but instead it holds a reference to it (composition). It also implements the expected interface.

There are pros and cons of each of these versions but in this article lets focus on more general concepts of the adapter pattern.

Now, what about the proxy pattern?

In general, it provides a surrogate of a given object in order to control the access to it in some way. Based on the way of controlling the access we can distinguish different types of proxy design pattern:

  • Remote proxy – it handles the interaction between remote objects.
  • Virtual proxy – it handles the situation when an object is expensive to create (lazy initialization).
  • Protection proxy - based on who calls the proxy, it controls the access to different methods.
  • Smart proxy – adds some extra operations when the objects is accessed.

Very important thing about the proxy pattern is the fact that the surrogate has the same interface as the real object.

To summarize. The adapter bridges the gap between two classes that are not compatible with each other. The proxy provides a surrogate to control the access to the real object.

Saturday, November 26, 2011

Re-throwing exceptions.

Today we will talk about re-throwing exceptions. In many cases, after examining a caught exception, it doesn't fulfill some requirements and we must re-throw it. This is a very basic and simple action in C# but for the Java developers there is a trap. In the aforementioned scenario, in Java we would just write:
throw e;
were e is the exception we caught.
Why don't we do the same in C# and see what will happen. Below is a sample code that illustrates such situation:
   class Program
{
void m1() { m2(); }
void m2() { m3(); }
void m3() { m4(); }
void m4()
{
throw new Exception("A sample exception.");
}
static void Main(string[] args)
{
try
{
new Program().m1();
}
catch(Exception e)
{
throw e;
}
}
}
Now lets execute it and examine the stack trace:
System.Exception was unhandled
Message=A sample exception.
Source=LearningCsharp
StackTrace:
at ConsoleApplication1.Program.Main(String[] args) in C:\Path\Program.cs:line 220
What did happen here? We somehow lost the whole stack trace. Now it looks like the exception was created within the Main method – in a real life scenario that may cause many problems when troubleshooting.
How to do it correctly in C# and preserve the whole stack trace? Here is the answer:
   class Program
{
void m1() { m2(); }
void m2() { m3(); }
void m3() { m4(); }
void m4()
{
throw new Exception("A sample exception.");
}
static void Main(string[] args)
{
try
{
new Program().m1();
}
catch(Exception e)
{
throw;
}
}
}
Yes! Simple
throw;
solves the issue. Now our stack trace will look as follows:
System.Exception was unhandled
Message=A sample exception.
Source=LearningCsharp
StackTrace:
at ConsoleApplication1.Program.m4() in C:\Path\Program.cs:line 210
at ConsoleApplication1.Program.m3() in C:\Path\Program.cs:line 207
at ConsoleApplication1.Program.m2() in C:\Path\Program.cs:line 206
at ConsoleApplication1.Program.m1() in C:\Path\Program.cs:line 205
at ConsoleApplication1.Program.Main(String[] args) in C:\Path\Program.cs:line 220
...
Looks much better – we can see which method thrown the exception and thus find the source of the issue.
So Java developers – bear that difference in mind and avoid confusion when analyzing a half empty stack trace! :)

Saturday, November 19, 2011

Exception handling – multiple catch.

Let's talk about the exception handling. Just to ensure that we are standing on the same planet – multiple catch of exception is a situation when we have a method that throws more than one checked exception and we want to handle some of them separetly. The following Java code shows such situation:

import java.util.ArrayList;
import java.util.List;

class Exception1 extends Exception {}
class Exception2 extends Exception {}
class Exception3 extends Exception {}

public class ExceptionHandling {
public static void throwsExceptions() throws Exception1, Exception2, Exception3 {
return;
}

public static void testMethod() {
try {
throwsExceptions();
}
catch(Exception1 e) {
// handle Exception1
}
catch(Exception2 e) {
// handle Exception2
}
catch(Exception e) {
// handle other exceptions.
}
}
}

But what if the logic for handling Exception1 and Exception2 is the same? In this case we get a dirty code duplication. Although, there is a simple remedy for that. What we could do, is to catch a base Exception class and then branch appropriately with if-else statement as the below code snippet presents:

public static void testMethod2() {
try {
throwsExceptions();
}
catch(Exception e) {
if(e instanceof Exception1 || e instanceof Exception2) {
// Do the common handling logic for Exception1 and Exception2
}
else {
// Handle other exceptions
}
}
}

So far so good. We don't have code duplication anymore. Just a note: the above examples use Java language but they also apply to C# - we would face the same issue/remedy when coding in it.
Now you may wonder what more can be done. As for C# not much really. In Java though, there is still some room for improvement. In Java 7 there has been introduced a new multiple catch mechanism so that we can catch multiple exceptions in one catch block! The following code sample shows the solution using Java 7:

public static void testMethod3() {
try {
throwsExceptions();
}
catch(Exception1 | Exception2 e) {
// Do the common handling logic for Exception1 and Exception2
}
catch(Exception e) {
// Handle other exceptions.
}
}

Here we can see how exceptions of type Exception1 and Exception2 are handled in one catch block using the '|' operator.
Summing up – a point for Java :)

Saturday, October 1, 2011

Named arguments in C#.

So today is the day. I'm kicking off with a new series of articles in the category C# vs. Java. Let's start with a feature called named arguments. In a nutshell, it let us name arguments that we are passing when invoking some method. When it can be useful? There are a few different scenarios. First of all, it may happen that we have a method that takes many arguments of the same type. It comes as no surprise that they can get mixed easily and normally compiler won't help us as long as the passed variables' types match the ones from the method signature. Another thing is just code readability – it is much easier to go through it when we can see the variable name from the method signature next to the variable that we are passing.

class NamedArgumentsExample
{
public static void AddStock(string companyShortName, int amount, double price)
{
}
static void Main(string[] args)
{
AddStock("MSFT", 100, 150);
AddStock("MSFT", amount: 100, price: 150);
}
}

In the above code we can see 2 method invocations – the first one without using named arguments. At first glance, it may be hard to get what are the values in the AddStock method invocation for. On the other hand, in the 9th line we can see with no problem that the first value is for the amount and the second for the price of a stock that we are adding.
As for Java, there is no such feature. I'm sure you can see, even from a very simple example above that it is useful. Of course, as with everything, one shouldn't overuse it but apply in a reasonable way, in cases where it will really add clarity.
That's it for today! Hope you enjoyed the post and have a happy Sunday!!

Thursday, September 29, 2011

Back in the game!


Yeah, that's right lads – I'm back to the blogging!! I know, it's been a while since the last post, over half a year but believe me – there was lots of things going on – changed a job, moved to a different country, finished my master thesis and stuff like that. Luckily nobody died so no big deal.
But cutting to the chase, now again, you will have an occasion to read about my thrilling and breathtaking adventures in the code.
You may wonder, what you can expect exactly. In my professional career I have switched to C# and so I came up with an idea to create a new category called “Java vs. C#” where I will be writing down my remarks about interesting differences in those languages and also in the platforms and frameworks associated with them. I have used C# for about 5 months so far and spotted already a few really useful features that Java does not have. On the other hand, I haven't noticed anything that Java has but C# does not – here, speaking only about the language itself.
Other than that I will still continue to bring up topics about software engineering in general and things I find worth sharing with you!
So stay tuned – the next post coming up soon!

Saturday, February 5, 2011

A tiny trick thanks to the autoboxing.

Today it will be short and tiny. The whole trick bases on the Java autoboxing feature. Let's say that we want to implement a method that checks whether a string that the passed reference points to, is evil. The first question that may pop up in your mind is when the string is evil? That mostly depends on you, in our example though, we will assume that it happens when it's equal to “666”. But wait, this article is not really about evilness. Let's go back to the way we should implement our method. The first important thing, is to check whether the reference is equal null. After that we can just invoke the equals() method inherited from the Object class and based on its result return true or false. A sample implementation could look like this:

public class StringTest {
static boolean isEvil(String evil) {
if(evil == null) {
return false;
}
return evil.equals("666");
}
}
But if we would like to get some advantage from the autoboxing feature in Java, we can easily get rid of the null check in our method. You probably ask why we can do that. It's simple – the null check is already done in the equals() method that the String class provides so why would we repeat it? To achieve the above, we have to force the “666” to be autoboxed and then invoke the equals() method on the new object against the passed reference. The following code shows the whole solution:

public class StringTest {
static boolean isEvilEnhanced(String evil) {
return "666".equals(evil);
}
}
It's shorter, still easily readable and what's more important, faster! (The autoboxing in the first example has to be done anyway, since the equals method takes a reference to the Object class)