Archive

Posts Tagged ‘multi-threaded’

Visual Studio 2010 Beta 2 is out!

October 21st, 2009 No comments

Microsoft has just released VisualStudio 2010 Beta 2 to MSDN Subscribers – aka Rosario.

msn_visual_studio_2010

I’m not sure why they’re going with the ULTIMATE moniker for Visual Studio, I still prefer the VS6 style Standard, Professional, Enterprise. Meh.

  • Microsoft Visual Studio 2010 Ultimate with MSDN
    The comprehensive suite of application lifecycle management tools for software teams to ensure quality results from design to deployment.
  • Microsoft Visual Studio 2010 Premium with MSDN
    A complete toolset for developers to deliver scalable, high quality applications.
  • Microsoft Visual Studio 2010 Professional with MSDN
    The essential tool for professional development tasks to assist developers in implementing their ideas easily. (Note: Visual Studio 2010 Professional will also be available without MSDN subscription)

Some of the more exciting things that are coming with Visual Studio 2010 are documented on MSDN or a better one would be Vikas Goyal’s post and also his .NET 4.0 coverage.. Personally the Parallel extensions are the most exciting bits for me. The new Java 7 work is concentrating heavily on concurrency and its good to see both camps pushing the boundaries.

{lang: 'en-GB'}
Share

InvokeRequired with anonymous delegates for threading in WinForms!

September 12th, 2009 2 comments

Here’s a little cookie from the cookie jar. To quote the legendary Jon Skeet from Threading with Windows Forms:

There are two different ways of invoking a method on the UI thread, one synchronous (Invoke) and one asynchronous (BeginInvoke). They work in much the same way – you specify a delegate and (optionally) some arguments, and a message goes on the queue for the UI thread to process. If you use Invoke, the current thread will block until the delegate has been executed. If you use BeginInvoke, the call will return immediately. If you need to get the return value of a delegate invoked asynchronously, you can use EndInvoke with the IAsyncResult returned by BeginInvoke to wait until the delegate has completed and fetch the return value.

Here’s a simple, uncluttered version you can utilise and reuse – this example just adds a list item to the listview.

        public void Add(ListViewItem item)
        {
            if (m_ListView.InvokeRequired)
            {
                m_ListView.BeginInvoke(new MethodInvoker(() => Add(item)));
            }
            else
            {
                m_ListView.Items.Add(item);
            }
        }

First we check whether we’re executing on the GUI thread or not (InvokeRequired), then execute a delegate thats parsed into the MethodInvoker calling itself using a lambda expression. This code is VS2008 compatible (.NET 2.0 +).

For a non lambda version:

      
        public void Add(ListViewItem item)
        {
            if (m_ListView.InvokeRequired)
            {
                m_ListView.BeginInvoke(new MethodInvoker(delegate
                                                             {
                                                                 Add(item);
                                                             }));
            }
            else
            {
                m_ListView.Items.Add(item);
            }
        }

The advantage of using an anonymous delegate is that by design, delegates are able to use local variables and parameters scoped in the containing method. Therefore we didn’t need to create a custom delegate with the signature to pass onto the method.

{lang: 'en-GB'}
Share

COOL TOOL: WinRAR 3.90 Beta released with some ubber goodness!

May 1st, 2009 3 comments

Rarlab, the genius’s behind the WinRAR product have released a new beta version (v3.9)  which brings some impressive new features:

Changes in Version 3.90 Beta 1:

  1. WinRAR version for Windows x64 is available. If you use Windows x64, it is strongly recommended to install 64 bit WinRAR version. It provides a higher performance and better shell integration than 32 bit version.
  2. RAR compression speed is improved for multi-core and multi-CPU systems. This improvement is most noticeable in Windows Vista and Windows 7 operating systems.
  3. “Remove duplicate folders from extraction path” option in “Settings/Compression” dialog is replaced by more universal “Remove redundant folders from extraction path” option. This option will eliminate redundant archive name based folders from extraction path if you unpack an archive with “Extract to DestName\” context menu command and if archive root folder contains only one folder and no files.
  4. Changes in “Extraction path and options” dialog:
    1. “New folder” button creates a new subfolder in currently selected folder;
    2. F2 key renames a selected folder in the folders tree;
    3. F5 key updated the tree pane contents;
    4. Del key removes a selected folder in the folders tree.
  5. You can enable “Show seconds” option in “Settings/File list” dialog if you wish to see seconds in file dates in file list in WinRAR shell.
  6. “Where to check for SFX archives” options group in “Settings/Integration/Context menus items” dialog lets you to control processing of SFX archives in context menus. For example, if you frequently right click “.exe” files on slow network disks, you can turn off “Network disks” options to minimize the delay before displaying the context menu.
  7. If you sort files by name in the file list in WinRAR shell, WinRAR will use the new logical file name sorting, same as in Windows Explorer, considering digits in file names by their numerical value. So files will be sorted as 1.txt, 2.txt, 10.txt instead of previous 1.txt, 10.txt, 2.txt. This new sort behavior is available in Windows XP Service Pack 2 and newer.
  8. Ctrl+W key combination can be used to close the main WinRAR window also as WinRAR viewer windows. “View as Windows text” shortcut in WinRAR viewer changed from Ctrl+W to Ctrl+I.
  9. New command line switch -r- disables recursion completely. So ‘rar a -r- arc dirname’ command will add only the empty dirname folder and ignore its contents. By default, if dirname does not include wildcards, RAR adds its contents even if -r switch is not specified.
  10. If used when extracting, the new command line switch -ai forces RAR to ignore file attributes. When using this switch, extracted files will always have attributes assigned by operating system to a newly created file by default.
  11. If output file name is not specified in “cw” command, console RAR will send comment data to stdout.
  12. When compressing stdin data with -si[name] switch, RAR sets modification time of archived entry to current system time. Previous RAR versions did not fill this field, resulting in meaningless modification time for stdin.
  13. Message displayed when you place the mouse cursor on WinRAR tray icon includes the archive name now. Previously only time left and total percent were displayed for archiving operations.
  14. Bugs fixed:
    1. WinRAR could fail to open tar or tar.gz archive if such archive contained a file larger than 8 GB;
    2. WinRAR context menu did not work properly in Windows 7 beta if icons in context menus were enabled and user clicked a file inside of Windows 7 Library folder;
    3. previous WinRAR versions failed to rename files having 5 or more continuous spaces in the name. WinRAR shell does not display such spaces for safety reasons, because they can hide an actual file extension. But this security measure prevented the rename command to work properly.

The primary bits that got my attention was the native x64 release and the improved multi-threaded support for compression (the first two items – bolded). So naturally I downloaded the Windows x64 release and had a stab at doing some benches. This was a very quick test.

Test Setup

Hardware

Specified in detail on the CPU-Z Validation page, otherwise an ASUS P5Q-Pro, Intel QX6850 @ 3Ghz with 8Gb of Corsair TWINX4096-6400C5 modules on two different hard disks:

Software

Windows Vista Ultimate x64 SP1 (current as of 01/05/2009)

WinRAR was set to ‘Best’ Compression and ‘Create Solid Archive’.

Test Methodology

I looked around for the best bunch of files I could find to compress – and that’s easily reproducible. Funnily/nerdy enough, the Microsoft Enterprise Library 4.1 (Download from Microsoft) source folder was chosen – with build files already included (binaries, pdbs etc).

Folder statistics

  • Files: 5148
  • Folders: 742
  • Size: 230Mb (241,576,303 bytes)
  • Size-on-Disk: 240 MB (251,727,872 bytes)

You can download a copy of the files from me, its 5.8Mb compressed. (UPDATE: Doh! wrong linkage!)

WinRAR Versions

WinRAR v3.80 (x86) vs WinRAR v3.90 Beta 1 (x64)

Test Results

WinRAR 3.9 Beta 1 (x64) vs WinRAR v3.80 (x86)

WinRAR 3.9 Beta 1 (x64) vs WinRAR v3.80 (x86)

The final output size of the RAR file was 5.28 MB (5,541,888 bytes).

Wow, 10 seconds shaved off, the cores were definately being utilised far greater than the previous releases.

Caveats

Unfortunately, the Beta  1 release (for me atleast) doesn’t properly register the shell context menus, so if you like right clicking and doing “Add to Archive” you might find that missing even though you told it to use it – I did make sure I uninstalled the 3.8 release prior to installing 3.9 and rebooted just to be sure, but no dice.

So maybe its not ready for prime time just yet, but 3.9 will surely rock your socks with some multi-core McLovin.

{lang: 'en-GB'}
Share

Design Patterns in C# & Java : The Singleton.

June 27th, 2008 1 comment

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.

{lang: 'en-GB'}
Share