Monday, January 30, 2012

Daemon Threads in Java

In normal circumstances, a Thread in executed until either it reaches the end of its void run() method or until void stop() is called (this method is deprecated and it's not recommended to use because it may trigger ThreadDeath errors).

Daemon threads are service providers for user-created threads. The main difference between daemon threads and non-daemon threads is that an application will end if the only remaining threads are daemon threads. The application will not end if there is at least one non-daemon thread running.

Any thread can become a daemon thread if one uses the method void setDaemon(boolean isDaemon). It is imperative to call this method before starting the thread. To check if a thread is a daemon thread you can simply call the method boolean isDaemon().

Also, it is to note that the void run() method must contain an infinite loop if you want your daemon thread to provide services as long as your application is opened.

Here's an example:
public class DaemonThread extends Thread
{
 public DaemonThread(String name)
 {
  super(name);
  this.setDaemon(true);
  this.start();
 }
 
 public void run()
 {
  while(true) //Keeps the daemon running
  {
   System.out.println("I am the Daemon " + getName() + "!");
   try 
   {
    Thread.sleep(100);
   } catch (InterruptedException e){}
  }
 }
}

Producer-Consumer Problem in Java

The producer-consumer problem is a "classic" multiprocessing problem involving two or more processes and a common resource who is a fixed-size buffer. The producer processes put data into the buffer and the consumer processes pop the data out of the buffer.

This processes need to be synchronized so the producers will not try to put data into the buffer when the buffer is full and consumer processes will not try to pop data out of the buffer when the buffer is empty.

In Java the synchronization can be achieved using the synchronized keyword. When a thread enters a synchronized method, it will activate a lock on that method so no other thread may enter it. The lock will be deactivated when the thread reaches the end of that method.

First we shall create the BufferResource class who will act similar to a stack:
public class BufferResource 
{
 private int[] buffer;
 private int lastIndex;
 private boolean isFull;
 
 public BufferResource(int size)
 {
  isFull = false;
  lastIndex = 0;
  buffer = new int[size];
 }
 
 public synchronized void pushData(int data)
 {
  while(isFull==true)
  {
   try
   {
    wait();
   }catch(InterruptedException ex){}
  }
  buffer[lastIndex] = data;
  lastIndex++;
  if(lastIndex>=buffer.length)
  {
   isFull=true;
   notifyAll();
  }
 }
 
 public synchronized int popData()
 {
  while(isFull==false)
  {
   try
   {
    wait();
   }catch(InterruptedException ex){}
  }
  lastIndex--;
  if(lastIndex==0)
  {
   isFull = false;
   notifyAll();
  }
  return buffer[lastIndex];
 }
}
The resource class contains an array to hold the data called buffer, an index called lastIndex to help pushing and popping and a boolean flag that will be set/unset when the lastIndex will be equal to the size of the array, respectively when lastIndex will be equal to zero.

The method void pushData(int data) will be called by the Producer class and will be used to fill the array with data. If the array is full, the Producer thread who entered the method will be blocked. When the last element of the array will be filled with data, the consumer threads will be waked up.

The method int popData() will be called by the Consumer class and will be used to remove data from the array. If the array is not full, the Consumer thread who entered the method will be blocked. When the array will be empty (after all data been popped), the producer threads will be waked up.

The Producer class will be implemented as:
public class Producer extends Thread
{
 private BufferResource buffer;
 private int iterations;
 
 public Producer(String name, int iterations, BufferResource buffer)
 {
  super(name);
  this.buffer = buffer;
  this.iterations = iterations;
 }
 
 public void run()
 {
  for(int i=0;i<iterations;i++)
  {
   buffer.pushData(i);
   System.out.println(this.getName() + " pushed " + i);
   try 
   {
    Thread.sleep((long)(Math.random()*1000));
   } catch (InterruptedException e) {}
  }
 }
}
The Producer class extends Thread and by doing so it needs to implement the interface Runnable. A Producer object needs to hold a reference to the common resource and may also hold a variable which specifies how many iterations it will do.

The Producer void run() method contains all the logic for a producer thread. The producer will push data into the buffer according to the specified number of iterations. After each push it will take a break for a random amount of time (maximum 1 second).

The Consumer class will be implemented as:
public class Consumer extends Thread
{
 private BufferResource buffer;
 private int iterations;
 
 public Consumer(String name, int iterations, BufferResource buffer)
 {
  super(name);
  this.buffer = buffer;
  this.iterations = iterations;
 }
 
 public void run()
 {
  for(int i=0;i<iterations;i++)
  {
   int val = buffer.popData();
   System.out.println(this.getName() + " poped " + val);
   try 
   {
    Thread.sleep((long)(Math.random()*1000));
   } catch (InterruptedException e) {}
  }
 }
}
The Consumer class is very similar to the Producer class. The main exception is that the Consumer will take data out of the buffer using BufferResource's method int popData().

The client for this application can be implemented as:
public class ProducerConsumerClient 
{
 public static void main(String args[])
 {
  BufferResource buffer = new BufferResource(5);
  Producer p1 = new Producer("Producer1",5,buffer);
  Producer p2 = new Producer("Producer2",5,buffer);
  Consumer c1 = new Consumer("Consumer1",5,buffer);
  Consumer c2 = new Consumer("Consumer2",5,buffer);
  p1.start();
  p2.start();
  c1.start();
  c2.start();
 }
}
It is very important to note, that in this implementation, in order to have all data consumed, the sum of iterations from the producers must be equal to the sum of iterations from the consumers.

If you try running the client, your output will be like:
Producer1 pushed 0
Producer2 pushed 0
Producer2 pushed 1
Producer2 pushed 2
Producer1 pushed 1
Consumer2 poped 1
Consumer1 poped 2
Consumer1 poped 1
Consumer2 poped 0
Consumer2 poped 0
Producer1 pushed 2
Producer2 pushed 3
Producer1 pushed 3
Producer2 pushed 4
Producer1 pushed 4
Consumer2 poped 4
Consumer1 poped 4
Consumer1 poped 3
Consumer2 poped 3
Consumer1 poped 2

Download source here.

Further reading:
Implementation of the Producer-Consumer using a BlockingQueue

Sunday, January 29, 2012

Creating Threads in Java

In Java, you can create a thread in two ways by:

1.Extending the Thread class

This is the easiest way to create a new thread. You simply need to create a new class which should inherit the Thread class from the java.lang package.

The Thread class implements the interface Runnable which contains the method void run(). The method void run() should contain all the actions and logic that your thread needs to perform.
public class MyThread extends Thread
{
 private int iterations;
 private long sleepTime;
 public MyThread(String s, int iterations, long sleepTime)
 {
  super(s);
  this.iterations = iterations;
  this.sleepTime = sleepTime;
 }
 public void run()
 {
  for(int i=0;i<iterations;i++)
  {
   System.out.println("Hi! My name is " 
         + this.getName() 
         + "! Iteration " + i);
   try
   {
    Thread.sleep(sleepTime);
   }catch(InterruptedException ex){}
  }     
 }
}
The class above takes as arguments the thread's name (which is transmitted to the superclass Thread), the number of iterations (practically how many times it will print a message) and a time in milliseconds which represents for how long the thread is going to wait after printing a message before starting another iteration.

As you probably already observed, the static void sleep(long timeInMilliseconds) method is called inside a try/catch block. The call must be done in this fashion because the sleep function throws an InterruptedException if the thread is interrupted by another thread.

You can create several threads of the type MyThread. Here's an example:
MyThread t1 = new MyThread("Slim",3,500);
MyThread t2 = new MyThread("Shady",2,250);
t1.start();
t2.start();
//Output
//Hi! My name is Slim! Iteration 0
//Hi! My name is Shady! Iteration 0
//Hi! My name is Shady! Iteration 1
//Hi! My name is Slim! Iteration 1
//Hi! My name is Slim! Iteration 2
It is very important to observe that a thread is started by calling the void start() method, NOT the void run() method which we implemented before.

2.Implementing the Runnable Interface

There are some cases where you may want your thread to inherit a specific object who doesn't inherit the Thread class. Since Java doesn't allow multiple inheritance you will not be able to inherit the object's class and the Thread class.
This problem can be solved by creating a subclass of your "specific object" that will also implement the Runnable interface.
Let us suppose that you have a class called CounterContext with the following implementation:
public class CounterContext 
{
 private int iterations;
 private long sleepTime;
 private String name;
 
 public CounterContext (String name, int iterations, 
         long sleepTime)
 {
  this.name = name;
  this.iterations = iterations;
  this.sleepTime = sleepTime;
 }
 
 public int getIterations(){return iterations;}
 public long getSleepTime(){return sleepTime;}
 public String getName(){return name;}
}
The subclass who will inherit CounterContext will implement the Runnable interface.
public class MyNewThread extends CounterContext implements Runnable
{
 public MyNewThread(String name, int iterations, long sleepTime)
 {
  super(name,iterations,sleepTime);
 }
 
 public void run() 
 {
  int iterations = getIterations();
  long sleepTime = getSleepTime();
  for(int i=0;i<iterations;i++)
  {
   System.out.println("Hi! My name is " 
         + this.getName() 
         + "! Itteration " + i);
   try
   {
    Thread.sleep(sleepTime);
   }catch(InterruptedException ex){}
  }  
 }
}
The MyNewThread does exactly the same thing as MyThread, except that MyNewThread will not be able to run as a thread by itself, but can serve as a constructor argument for a Thread object. The newly created Thread object will behave exactly like a MyThread object (since the void run() methods are almost identical for both MyNewThread and MyThread).
Thread t1 = new Thread(new MyNewThread("Slim",3,500));
Thread t2 = new Thread(new MyNewThread("Shady",2,250));
t1.start();
t2.start();
//Output
//Hi! My name is Slim! Itteration 0
//Hi! My name is Shady! Itteration 0
//Hi! My name is Shady! Itteration 1
//Hi! My name is Slim! Itteration 1
//Hi! My name is Slim! Itteration 2

Simulating Multiple Inheritance in Java

As you probably know, Java has no mechanism for "true" multiple inheritance like C++, but it can be somewhat "simulated" using abstract classes and interfaces.

Let us suppose that we want to create a class called Ballerina. A ballerina has attributes like name, age, height and weight and behaviors like dancing, running, jumping and sleeping. The Ballerina class should inherit two classes: Athlete and Dancer. The Athlete and Dancer classes have some things in common like the fact that both athletes and dancers have a name and an age and they both have to sleep. The thing that differentiates athletes from dancers is the fact that athletes run and jump, while dancers have to dance.

In C++, we could had the Ballerina class inherit the Athlete and Dancer classes directly through multiple inheritance (and since the base classes have common attributes one of them would had been inherited virtually), but like I said before this mechanism is not available in Java.

In order to have a good OO design, we need to create a base class which should contain the common attributes and behaviors found in athletes and dancers. Since such a class doesn't need to be instantiated, it should be declared as abstract. We shall call this class Human.
public abstract class Human
{
 private String name;
 private int age;
 
 public Human(String name, int age)
 {
  this.name = name;
  this.age = age;
 }
 
 public abstract void sleepNow();
}
If we wouldn't need to create the Ballerina class, we could simply create an Athlete class to extend the Human class. But since both ballerinas and athletes run and jump, we should declare first an interface for this behaviors.
public interface IAthlete 
{
 public void run();
 public void jump();
}
The class Athlete should be then like:
public class Athlete extends Human implements IAthlete
{
 public Athlete(String name, int age) 
 {
  super(name, age);
 }
 public void sleepNow()
 {
  System.out.println("Athlete sleeps");
 }
 public void run() 
 {
  System.out.println("Athelete runs");
 }
 public void jump() 
 {
  System.out.println("Athlete jumps");
 }
}
We shall apply the same logic for dancers. First we shall define an interface to contain the specific behaviors of a Dancer:
public interface IDancer 
{
 public void dance();
}
And then we shall define a class to implement this behaviors:
public class Dancer extends Human implements IDancer
{
 public Dancer(String name, int age) 
 {
  super(name, age);
 }
 public void dance() 
 {
  System.out.println("Dancer dances");
  
 }
 public void sleepNow()
 {
  System.out.println("Dancer sleeps");
 }
}
Now, we can define the Ballerina class as a class that inherits the Human abstract class and implements the behavior of dancers and athletes:
public class Ballerina extends Human implements IAthlete, IDancer
{
 private int height, weight;
 public Ballerina(String name, int age, int height, int weight) 
 {
  super(name, age);
  this.height = height;
  this.weight = weight;
 }
 public void run()
 {
  System.out.println("Ballerina runs");
 }

 public void dance() 
 {
  System.out.println("Ballerina dances"); 
 }

 public void jump() 
 {
  System.out.println("Ballerina jumps"); 
 }

 public void sleepNow()
 {
  System.out.println("Ballerina sleeps");
 }
}
Even if the Ballerina class can't inherit directly from Dancer and Athelete, we can use the interfaces IAthlete and IDancer "like base classes" to reference Athlete and Ballerina object respectively Dancer and Ballerina objects.
IDancer d1 = new Dancer("John",32);
IDancer d2 = new Ballerina("Joanna",20,170,55);
d1.dance();
d2.dance();
IAthlete a1 = new Athlete("Mike",22);
IAthlete a2 = (IAthlete)d2; //Ballerina implements both interfaces
a1.jump();
a2.jump();
//Output
//Dancer dances
//Ballerina dances
//Athlete jumps
//Ballerina jumps
Also it is to note that a Human reference can reference both Dancer and Athlete and also Ballerina.
Human h1 = new Dancer("John",32);
Human h2 = new Athlete("Jimmy",33);
Human h3 = new Ballerina("Irina",21,170,55);
h1.sleepNow();
h2.sleepNow();
h3.sleepNow();
//Output
//Dancer sleeps
//Athlete sleeps
//Ballerina sleeps

Thursday, January 5, 2012

Language Compile Options for the VB.NET Compiler

There are four language compile option for VB.NET:

/optioncompare
This option declares the default comparison method used when comparing string data. There are two choices: binary and text

If the binary comparison method is chosen, the strings will be compared according to their binary representation. This method is the fastest, but may lead sometimes to some unwanted results if you use the Unicode set. This happens because the strings are compared character by character according to their Unicode value which would be something like:
A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø
So, if you think that À should come after A and before B, you should not use the binary comparison method. Also binary comparison is case sensitive.

If the text comparison method is chosen, the strings will be compared according based on a case insensitive text sort order determined by the system's locale. This is something like:
(A=a) < (À = à) < (B=b) < (E=e) < (Ê = ê) < (Z=z) < (Ø = ø)
Console.Write("À" < "B")
'Output: True (when using Text Compare)
'Output: False (when using Binary Compare)
/optionexplicit
If this option is enabled all variables must be declared using the Dim or ReDim statements. If one tries to use an undeclared variable, an error will occur at compile time. If this option is disabled, one can use a variable without declaring it first using Dim or ReDim.
i = 3
Console.Write(i)
'Will trigger an error if Option Explicit is On
'Will not trigger an error if Option Explicit is Off
/optionstrict
When Option Strict is On, implict narrowing conversions, late binding and implicit typing that results to Object will cause a compile-time error. If Option Strict is Off, you will receive warnings or run-time errors instead of compile-time errors;
'Narrowing conversion example
Dim a As Long = 5
Dim b As Integer = a
'Option Strict On => Will cause error, can be corrected by
'Dim b As Integer = Ctype(a,Integer)
'Option Strict Off => Will raise a warning

'Late binding example
Dim text As Object
text = New Object
text = "abc"
'Option Strict On => Will cause compile error
'Option Strict Off => Will cause a runtime error

'Implicit typing that results to Object example
Dim x
'Option Strict On => Will cause compile error
'Option Strict Off => x will be equal to Nothing
/optioninfer
When Option Infer is On, the compiler will guess (infer) the type of an object if the type is unspecified according to a value assigned to it. When Option Infer is Off, the compiler will not try to guess the type of the object if you don't specify it and will cast it as Object. (if Option Strict is On this may cause compile-time errors because this is an implicit typing that results to Object).
<
Dim number = 3
Dim text = "abc"
Dim letter = "c"c
Dim real = Math.PI
'If Option Infer is On
'number will be of type int
'text will be of type string
'letter will be of type char
'real will be of type double
'If Option Infer is Off
'number,text,letter,real will be considered as Object
To set the compile options directly from Visual Studio, one must go to the project's properties (either by right-clicking on your project and selecting the Properties item or by going toProject -> <name_of_your_project> Properties in the menu bar) and then to the compile panel.
In command line, you simply need to specify the options as arguments to the compiler:
Alternatively you can specify this options directly into the code. Using them this way, the new options will overwrite the old options specified as compiler arguments (or set in Visual Studio).
Option Strict Off
Option Infer On
Option Explicit Off
Option Compare Binary
Module Program
    Public Sub Main(ByVal args As String())
        Console.Write("Hello compiler world!")
    End Sub
End Module

Wednesday, January 4, 2012

Setting the Command-Line Compiler for VB.NET in Windows

In order to set the VB.NET compiler for command-line usage you first need to have it installed. You can download the .NET 4.0 framework from here.

You could also get the compiler you installed a Visual Studio version that contains Visual Basic. You can download free of charge the Visual Basic Express Edition from here.

After you installed it, you need to do the following steps:
  1. Go to My Computer -> Right click on Properties -> Advanced Settings
  2. Click on the Environment Variables button. (see Caption 1 for details)
  3. Select the PATH variable from user variables and click on the Properties.
  4. Insert the path to file vbc.exe (you will probably find it in ...\Windows\Microsoft.NET\Framework\<.NETVersion>\vbc.exe) after you put a semicolon in front of it. In the end it will look like ;C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe 
  5. Click OK ( see Caption 2 for details).
  6. Enjoy command-line compiling :)

Caption 1
Caption 2

Related Posts Plugin for WordPress, Blogger...