pik from GitBash – 0.30 UPDATE

actor nerd

Pik is a ruby version manager for windows. With version 0.30 I had to do the following to get it to work with GitBash. Basically I had to edit my .bashrc and create a $USERPROFILE/.pik/.pikrc.

In the .bashrc I added the following:

[[ -s "$USERPROFILE/.pik/.pikrc" ]] && source "$USERPROFILE/.pik/.pikrc"

And in the .pikrc:

#!/bin/sh
pik_path="/c/pik"

function pik  {
  "$pik_path/pik_runner.exe" pik.sh $@
  [[ -s "$USERPROFILE/.pik/pik.sh" ]] && source "$USERPROFILE/.pik/pik.sh"
}

Having quotes around the paths is only necessary if you have spaces in the path (like “Program Files”).

Thread Safe Lazy Initialization in .NET

A quick article on creating an Optimized Thread Safe Lazy Initialization.

When to be Lazy? Simple, you may have a class which is expensive to create. You don’t want to incur the performance cost of instantiating this Expensive object when you create an instance of a class which depends upon the Expensive class.

When this is the case, you may wish to only create the instance of the Expensive object if and when you need to use it.

Lazy Initialization via Property (Not Thread Safe):

public class Foo
{
    private Expensive _expensive;
    public Expensive Expensive
    {
        get
        {
            return _expensive ?? (_expensive = new Expensive());
        }
    }
}

Think about what could happen within the ‘Expensive’ property if 2 Threads accessed it at once. You may find that each thread bypasses the null checkout of the _expensive field and a new instance is created twice each time being placed into the _expensive field.

Using a Lock:

public class Foo
{
    private readonly object _expensiveLock = new object();
    private Expensive _expensive;
    public Expensive Expensive
    {
        get
        {
            lock (_expensiveLock)
            {
                return _expensive ?? (_expensive = new Expensive());  
            }
        }
    }
}

This will ensure a single Thread is able to check and instantiate the _expensive field at a time, ensuring we do not run into subtle errors regarding double instantiation.

This will also ensure that new Expensive(); is only called once which makes this a very simple solution for ensuring we only create 1 instance, and consuming threads will obtain reference to same instance.

Using Lazy<T>:

In .NET 4.0 the Lazy<T> class was made available to help with this very problem. It has an overload which takes a boolean parameter for isThreadSafe that internally implements a micro-optimized version of the pattern described above.

public class Foo
{
    private readonly Lazy<Expensive> _expensive =
        new Lazy<Expensive>(()=> new Expensive(), true);
    public Expensive Expensive
    {
        get { return _expensive.Value; }
    }
}

This, under the hood, implements Double-check locking which performs and additional volatile read to avoid the cost of obtaining a lock if the object already exists.

Example of Double-checked locking:

volatile Expensive _expensive;
public Expensive Expensive
{
  get
  {
    if (_expensive == null)             // First check (outside lock)
      lock (_expenseLock)
        if (_expensive == null)         // Second check (inside lock)
          _expensive = new Expensive();
    return _expensive;
  }
}

This will ensure a lock is not taken on the Read if _expensive field is already initialized.

Further Optimization using LazyInitializer

We can leverage the System.Threading.LazyInitializer which is a static class that works in much the same as System.Lazy<T> except for its functionality is exposed via a single static method that works directly on the field in your own type.

This allows us to forgo a layer of indirection, improving performance in cases where extreme optimization is required.

These routines avoid needing to allocate a dedicated, lazy-initialization instance, instead using references to ensure targets have been initialized as they are accessed.

To use LazyInitializer, call EnsureInitialzied before accessing the field, passing a reference to the field and the factory delegate:

using System.Threading;

public class Foo
{
    private Expensive _expensive;
    public Expensive Expensive
    {
        get
        {
            // Double-checked locking
            LazyInitializer.EnsureInitialized(ref _expensive,
                () => new Expensive());
            return _expensive;
        }
    }
}

“Race to Initialize” instead of “Double-check locking”

It is faster on multi-cores because it can be implemented entirely without locks. It’s slower when more threads race to initialize than you have cores.

Note: The Expensive object may be created twice (or more times).

See: MSDN – Lazy Initialization for a summary table of Lazy Thread Safety Modes.

public class Foo
{
    private Lazy<Expensive> _expensive =
        new Lazy<Expensive>(() => new Expensive(),
           LazyThreadSafetyMode.PublicationOnly);
    public Expensive Expensive
    {
        get { return _expensive.Value; }
    }
}

Under the hood this is still Fully thread-safe; but threads race to initialize the value. Specifying LazyThreadSafetyMode.PublicationOnly allows multiple threads to attempt to initialize the Lazy instance. Only one thread can win this race, and all the other threads receive the value that was initialized by the successful thread.

Example “Race to Initialize” pattern:

volatile Expensive _expensive;
public Expensive Expensive
{
  get
  {
    if (_expensive == null)
    {
      var instance = new Expensive();
      Interlocked.CompareExchange (ref _expensive, instance, null);
    }
    return _expensive;
  }
}

Albahari sums this up very well:

The advantage of this technique is that it’s even faster (on multicores) than double-checked locking — because it can be implemented entirely without locks. This is an extreme optimization that you rarely need, and one that comes at a cost:

  • It’s slower when more threads race to initialize than you have cores.
  • It potentially wastes CPU resources performing redundant initialization.
  • The initialization logic must be thread-safe (in this case, it would be thread-unsafe if Expensive’s constructor wrote to static fields, for instance).
  • If the initializer instantiates an object requiring disposal, the “wasted” object won’t get disposed without additional logic.

Albahari – Threading – Lazy Initialization

Further Reading…

MSDN – Lazy Initialization

Albahari – Threading – Lazy Initialization

C# 5.0 in a Nutshell

Naiad & Differential Dataflow

Naiad is an investigation of data-parallel dataflow computation in the spirit of Dryad and DryadLINQ, but with a focus on incremental computation. Naiad introduces a new computational model, differential dataflow, operating over collections of differences rather than collections of records, and resulting in very efficient implementations of programming patterns that are expensive in existing systems.
[Source: Microsoft Research]

“Our goal with Naiad was to address one of the recurring requests for systems like Dryad and DryadLINQ, incremental recomputation, but in so doing found that the necessary mechanisms gave rise to a new computational model, differential dataflow, capable of efficiently processing substantially more complex computations than current systems support, namely incremental and arbitrarily nested iterative dataflow computation.”

Microsoft Researcher Frank McSherry

Download Naiad

Going Deeper… Download these Whitepapers:

“Differential Dataflow”

“Existing computational models for processing continuously changing input data are unable to efficiently support iterative queries except in limited special cases. This makes it difficult to perform complex tasks, such as social-graph analysis on changing data at interactive timescales, which would greatly benefit those analyzing the behavior of services like Twitter. In this paper we introduce a new model called differential computation, which extends traditional incremental computation to allow arbitrarily nested iteration, and explain—with reference to a publicly available prototype system called Naiad—how differential computation can be efficiently implemented in the context of a declarative data-parallel dataflow language. The resulting system makes it easy to program previously intractable algorithms such as incrementally updated strongly connected components, and integrate them with data transformation operations to obtain practically relevant insights from real data streams.”

“Composable Incremental and Iterative Data-Parallel Computation with Naiad”

“We report on the design and implementation of Naiad, a set of declarative data-parallel language extensions and an associated runtime supporting efficient and composable incremental and iterative computation. This combination is enabled by a new computational model we call differential dataflow, in which incremental computation can be performed using a partial, rather than total, order on time.

Naiad extends standard batch data-parallel processing models like MapReduce, Hadoop, and Dryad/DryadLINQ, to support efficient incremental updates to the inputs in the manner of a stream processing system, while at the same time enabling arbitrarily nested fixed-point iteration. In this paper, we evaluate a prototype of Naiad that uses shared memory on a single multi-core computer. We apply Naiad to various computations, including several graph algorithms, and observe good scaling properties and efficient incremental recomputation.”

Reinstalling Brew (the doctor said so)

RVM was starting to cry about my brew install, I ran

brew doctor

and the list of symptoms were as long as my arm. Too much corruption by MacPorts and Fink most likely the cause. It was time for a fresh install (or spend the rest of today fixing the issues manually).

Uninstall

cd `brew --prefix`
rm -rf Cellar
brew prune
rm -rf Library .git .gitignore bin/brew README.md share/man/man1/brew
rm -rf ~/Library/Caches/Homebrew

http://superuser.com/questions/203707/how-to-uninstall-homebrew-osx-packet-manager

Reinstall

ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)"

https://github.com/mxcl/homebrew/wiki/Installation

Done did.

Launch Sublime Text 3 from oh-my-zsh

actor nerd I use oh-my-zh, I like the fact it has a plugin system. I want to keep ‘st’ alias for Sublime Test 2 until Sublime Text 3 is stable. Doesn’t mean I don’t want to play with ST3 in the meantime.

Sublime Text 3 is in beta and is open to those who paid for it. Downloaded the latest build and renamed it to ‘Sublime Text 3′ and then installed it..

I use the sublime text plug-in that comes with oh-my-zsh. I opened up the oh-my-zsh folder in my editor to have a wee poke about:

open oh-my-zsh in editor

To support ‘st3′ alias I simply put the following at the bottom of the sublime plug-in:

local _sublime_darwin_subl3=/Applications/Sublime\ Text\ 3.app/Contents/SharedSupport/bin/subl

if  [[ $('uname') == 'Darwin' ]]; then
  # Check if Sublime is installed in user's home application directory
  if [[ -a $HOME/${_sublime_darwin_subl3} ]]; then
    alias st3='$HOME/${_sublime_darwin_subl3}'
  else
    alias st3='${_sublime_darwin_subl3}'
  fi
fi
alias stt3='st3 .'

sublime oh-my-zh plug-in

Suki Tea – Lemongrass & Ginger Twist

actor coffee

suki-tea-logo

A really nice tea.. A very layered taste, citrus, then spice, sweet then fresh mint.

A really nice tea.. A very layered taste, citrus, then spice, sweet then fresh mint.

This tea was suggested to us by a customer who had tried something with lemon and ginger in it, we started trying different recipes and ingredients and six months later we are very proud to say we have created something quite unique. A lemongrass and subtle ginger taste to start with, then a sweetness and little kick from liquorice and pepper finished with fresh spearmint and peppermint. Definately worth a try.

Buy some here!

Posted in Tea |