Archive

Archive for the ‘Java’ Category

The Slick New DeveloperFusion.com is ’soft-launched’

September 29th, 2008

DeveloperFusion.com

DeveloperFusion has just soft-launched its slick new look and feel, go take a looksy and drool. From the humble beginnings, to the golden years and the times of change we have finally come to the slick new Web 2.0 era - maybe a tad late but damn it was worth the wait!

James is now full time at DF working away at making DF the greatest community driven site around.

.NET / CLR / C#, Design Patterns, Developer, Java, Tools / Products, Web / Internets, software , , , , ,

Managed Operating Systems & COSMOS - C# Open Source Managed Operating System

September 21st, 2008

Writing an operating system in Managed Code is not entirely a new concept but its quite an interesting one. The fact that we have AOT compilers gives us this ability to write such things. This post is a little guided tour or information dump on COSMOS as I worked through the initial bits this weekend.

Background Information

Unlike a JIT compiler - where the initial source (say C# or Java) gets translated into an IL (like MSIL in .NET or Bytecode in Java) which then gets to native code when run (via the .NET CLR or the Java VM), an AOT compiler transforms the source directly to native code - which implies its compiled for a specific architecture and feature-set (eg. x86 binary). Currently there are a couple (in .NET land) to choose from - SharpOS AOT and the IL2CPU project written by the Cosmos guys.

This ensures that the OS can be written entirely from managed code, unlike other attempts like JNode, JavaOS (both of which are Java based and include some ASM & C routines for the initial boot) and the Microsoft Singularity project - which uses some Assembler & C (for the interupt dispatcher) and C++ code to get things moving.

Pweety Screenshots

Side by side pretty pictures of some Managed OSs:

COSMOS

This weekend I took a bit of a look-c of COSMOS, which differs greatly from Singularity. The COSMOS compiler - called IL2CPU, written in C# - converts all the IL code generated to assembler (not to be confused with a .NET Assembly!), thereafter the assembler files are processed by NASM which generates compliant native x86 code. Eventually though, the COSMOS guys hope to generate native directly without the need for NASM. This process is quite streamlined and if you download the COSMOS User Kit you can get COSMOS + booted up and running in minutes! Its way coool!

The User Kit page has all the goss on getting it setup, I tried out Milestone 2, but some helpful  hints…

  • Dont install to the default Program Files folder (especially on Vista!) put it into a non-Windows oriented folder.
  • After installing and integrating into VS.NET, use the QEmu option to try it out - VMWare resources arent distributed it seems, as QEmu is already shipped theres nothing more to do.

After you have it installed, load VS.NET and create a new ‘COSMOS Boot’ project. The default template is shown below:


using System;
using Cosmos.Build.Windows;

namespace CosmosHelloWorld
{
class Program
{
#region Cosmos Builder logic
// Most users wont touch this. This will call the Cosmos Build tool
[STAThread]
static void Main(string[] args)
{
var xBuilder = new Builder();
xBuilder.Build();
}
#endregion

// Main entry point of the kernel
public static void Init()
{
Cosmos.Kernel.Boot.Default();
Console.WriteLine("Welcome! You just booted C# code. Please edit Program.cs to fit your needs.");
while (true)
;
}
}
}

Essentially, this boots the COSMOS kernel and displays “Welcome! You just booted C# code. Please edit Program.cs to fit your needs.”, quite simple. Run it and you’ll get the COSMOS Build Options window to help you deploy it - for simplicity select QEMU, hit build and watch the magic of the IL2CPU and other tools come together and build your OS and run QEMU. The output should be something like this (with differing paths ofcourse!):

BuildPath = ‘D:\R&D\Cosmos User Kit\’
ToolsPath = ‘D:\R&D\Cosmos User Kit\Tools\’
ISOPath = ‘D:\R&D\Cosmos User Kit\ISO\’
PXEPath = ‘D:\R&D\Cosmos User Kit\PXE\’
AsmPath = ‘D:\R&D\Cosmos User Kit\Tools\asm\’
VMWarePath = ‘D:\R&D\Cosmos User Kit\VMWare\’
VPCPath = ‘D:\R&D\Cosmos User Kit\VPC\’
Now compiling
Initializing IL2CPU… This may take a minute so please wait for further status…

Recognized Plug methods:

System_Boolean__System_Array_TrySZBinarySearch_System_Array__System_Int32__System_Int32__System_Object__System_Int32__

IL2CPU Run took 00:00:05.3281467
Please wait…executing D:\R&D\Cosmos User Kit\Tools\nasm\nasm.exe…
Please wait…executing D:\R&D\Cosmos User Kit\Tools\cygwin\ld.exe…
Now creating ISO
Try removing ‘D:\R&D\Cosmos User Kit\cosmos.iso’
Try removing ‘D:\R&D\Cosmos User Kit\ISO\output.bin’
Try copying ‘D:\R&D\Cosmos User Kit\output.bin’ to ‘D:\R&D\Cosmos User Kit\ISO\’
Running mkisofs
Please wait…executing D:\R&D\Cosmos User Kit\Tools\mkisofs.exe…
Please wait…executing D:\R&D\Cosmos User Kit\Tools\qemu\qemu.exe…
Press enter to continue.

The Build agent runs IL2CPU which outputs the ASM, which then goes through to NASM who hands it over to GNU Linker. Then we bake an ISO which gets booted by QEMU. Couldn’t be easier :-)

A man can dream Oh yes a man can dream

There are some incredibly exciting ideas are floating around about how to make the most of COSMOS and what can be fully realised on the Scenarios Page and an interview at Obsethryl Labs on COSMOS and another on SharpOS which is interesting reading.

Next time I’ll start poking around some more and see where it gets me.

.NET / CLR / C#, Developer, Java, Operating Systems, Windows , , , , , , ,

Design Patterns in C# & Java : The Singleton.

June 27th, 2008

So its back to reality of living back home! I’ve been slowly going through my mail and replying to everyones messages, one in particular stood out from someone asking me about how to implement the Singleton pattern properly in C# and Java.

First of all, lets go through what the Singleton Design Pattern is and where its used.

Singleton Design Pattern

The Singleton Pattern is quite simply a design pattern that allows only one instance of itself to be created per application pool or application instance and provides one point of access to the single unique instance. I guess one could conclude that the Singleton is like Neo, it is “the one”.

From the Gang of Four - Design Patterns book (the Bible when it comes to talk about commonly used Design Patterns!) the definition or intent of the Singleton pattern is described as:

Ensure a class only has one instance, and provide a global point of access to it.

If you haven’t already got it on your bookshelf, I’d highly recommend buying the book!

Usage

When the Singleton Design Pattern comes in handy is when we want to ensure that a class is instantiated once and optionally in a lazily fashion - when the instance is first accessed, unlike Global variables (bad bad bad!) where it will always consume memory regardless! Alternatively we could opt to have the Singleton class instantiated as soon as the class is loaded which isn’t quite so lazy. How you chose to load it is completely your call based on how ‘heavy’ the load-tax is on the class itself and if there is a performance penalty etc.

Implementation

In order to implement a class as a Singleton object we need to do a few things to make sure we stay consistent:

  • The constructor for the class has to be marked private (or protected), this ensures that the class is not able to be instantiated outside itself - compiler-level restriction.
  • In C#, mark the class as sealed so that no other classes can “extend” or inherit this Singleton class.
  • In Java, override the clone method to ensure that the class is not cloned (as the object class contains a protected clone method).
  • Implement an accessor method to allow classes to access this class, usually Instance() in C# or getInstance() in Java.
  • In a multi-threaded application, ensure that the checking and instantiating initially is mutually exclusive (thread-safe). This is easily accomplished in C# and in Java 5+ as we will see soon.

There are two ways to implement the loading of the class, one is to instantiated it as soon as the class itself is loaded and the other lazily loaded when another class needs to use it (avoiding loading it before-hand).

Implementations - Java Bare-Essential (Non-Thread Safe)

So lets look at how to implement the pattern in Java first. Initially the plain bare-essential version which does not factor in thread-safety at all and uses Lazy-loading.


public class Singleton {

protected Singleton() { }

private static Singleton _instance = null;
/**
* @return The unique instance to this class.
*/
public static Singleton getInstance() {
if(null == _instance) {
_instance = new Singleton();
}
return _instance;
}

/**
* To avoid an inherted class from trying to
* clone the class, we override the object.clone
* method and throw an exception.
*/
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
}

Implementations - Java Thread Safe

Now how about a thread-safe implementation we add the synchronized keyword into the method declaration as per Java coding standard.


/**
* @return The unique instance to this class.
*/
public static synchronized Singleton getInstance() {
if(null == _instance) {
_instance = new Singleton();
}
return _instance;
}

But if your using Java 5, there is yet another way which uses volatile double checked locking as described on Wikipedia, however using this prior to Java 5 is not recommended as it is broken.

A simpler and more effective way is to use a subclass to hold the instance safely, this ensures that the class is only loaded when the getInstance() method is called (Lazy-loaded) and no earlier. Here we declare a class called SingletonContainer to hold a single static final variable that has an instance of the class Singleton. The JVM will only create an instance of Singleton when getInstance() is called.


public class Singleton {
protected Singleton() {}

/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.instance , not before.
*/
private static class SingletonContainer {
private final static Singleton _instance = new Singleton();
}

public static Singleton getInstance() {
return SingletonContainer._instance;
}

public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
}

Implementations - C# Bare-Essentials

Moving onto a C# version, first up is a bare-essentials version based on our original list of points needed to implement the Singleton object.


public sealed class Singleton
{
private static Singleton _Instance = null;

private Singleton() { }

public static Singleton Instance
{
get
{
if (null == _Instance)
{
_Instance = new Singleton();
}
return _instance;
}
}
}

Easy done, but as mentioned earlier this is _not_ thread-safe.

Implementations - C# Thread-Safe

Lets work on a thread-safe version using a lock. This ensures that all reads happen logically after a lock is acquired and unlocking that all writes happen logically before release.


public sealed class Singleton
{
private static Singleton _Instance = null;
private static readonly object _Lock = new object();

private Singleton() { }

public static Singleton Instance
{
get
{
lock(_Lock) {
if (null == _Instance)
{
_Instance = new Singleton();
}
return _instance;
}
}
}
}

What about a thread-safe version without the use of a lock? Sure, quite possible in .NET with the use of the readonly keyword.

Const vs ReadOnly fields in C#

Lets step back a bit and go into the readonly keyword first. The readonly keyword is often mixed with the const keyword, but whilst they may seem to do the samething they offer very different ways of achieving the final result, a read-only field. A const field can only be initialised when declared (compile-time constant) where as a readonly field can be initialised either at declaration time or in the constructor of the class. This is a very important distinction as a readonly field means that it may be different each time the class is loaded, where as a const field is always going to be the same unless you change the constant and recompile the assembly.

Implementations - C# Thread-Safe readonly

OK back to the C# Thread-Safe version this time without locks using the readonly keyword.


public sealed class Singleton
{
private static readonly Singleton _Instance = new Singleton();

private Singleton() { }

public static Singleton Instance
{
get
{
return _Instance;
}
}
}

So when this class is loaded by the CLR, the _Instance variable is initialised and a new instance is created. Therefore when the Instance method is invoked we know that it will always exist.

Implementations - C# Thread-Safe Lazy-Loading readonly

Finally, an implementation that uses Lazy-Loading to enhance the previous version one more time!


public sealed class Singleton
{
private Singleton() { }

public static Singleton Instance
{
get
{
return SingletonContainer._Instance;
}
}
class SingletonContainer {
static SingletonContainer() {}
internal static readonly Singleton _Instance = new Singleton();
}
}

So there we have it, some examples and usage of Singletons in different situations. For optimal use, one should document whether having a lazy-loaded or class-loading solution is beneficial. I tend to use the threadsafe readonly version (class loading) more than usual.

.NET / CLR / C#, Design Patterns, Developer, Java , , , , , , , , , , , , , , , , , , , ,