Object pooling is a design pattern that can be used when the instantiation of objects is an expensive operation, or when memory allocation and garbage collection can be issues. An object pool keeps a set of objects alive ready for use for the program so that these objects don’t need to be created every time they are needed.

Instead, the program can ask for one of these objects at runtime, use it, and then return it to the object pool. Later, the same object will be available again, ready to be used.

More than one thread

It’s all well and good when only one thread has access to an object pool, but what happens when more than one thread need to access a pool to get an object quickly? Race conditions could occur when both threads access the pool at the same time and received the same object back. At this point both threads are using the same object and Bad Things™ will happen!

This is because the pool is not thread safe and it doesn’t prevent its access to only one thread at a time. So how to solve this?

Use a Lock

A straightforward way to solve this issue is to use a lock statement which will literally lock the access to the pool and force any other thread who are not in possession of such lock, to wait for its release before resuming execution.

        private readonly object fooLock = new object();

        void GetPooledObject()
        {
            lock( fooLock )
            {
                // Grab pooled object and return it
            }
        }

This will lock everything wrapped around the lock scope, but it is not as efficient as it could be: each thread will have to wait for the previous one to release the lock before being able to proceed. Also if thread-fairness is something of importance to you, probably using a lock is not the best decision.

Luckily for us, the .Net framework provides us with data structures that are already thread-safe!

Concurrent Collections

The .NET Framework 4 comes with a whole lot of collections which are concurrent and thread safe. This means that they can be accessed by multiple threads at the same time.

Turns-out that most of these collections are also lock-free, and this should give you better performance too.

If you want to know more about these collection, go check the links below and have a poke around the System.Collections.Concurrent namespace.

ConcurrentPool.cs

    public class ConcurrentPool<T> where T : IResettable
    {
        // -----------------------------------------------------------------
        // Data
        // -----------------------------------------------------------------
        ConcurrentBag<PooledObject<T>> mPool = new ConcurrentBag<PooledObject<T>>();
        Func<T> mFactory;

        // -----------------------------------------------------------------
        // Constructors
        // -----------------------------------------------------------------
        public ConcurrentPool( Func<T> inFactory )
        {
            mFactory = inFactory ?? throw new Exception( "[Concurrent Pool] Factory Function is null" );
        }

        // -----------------------------------------------------------------
        // Functions
        // -----------------------------------------------------------------
        public PooledObject<T> Get()
        {
            if( mPool.TryTake( out PooledObject<T> returnObject ) )
            {
                return returnObject;
            }

            T newObject = mFactory();
            PooledObject<T> pooledObject = new PooledObject<T>( newObject, this );

            return pooledObject;
        }

        // -----------------------------------------------------------------
        public void Return( PooledObject<T> inToReturn )
        {
            if( inToReturn != null )
            {
                mPool.Add( inToReturn );
            }
        }
    }

Concurrent pool is a template class, which means it can be used with different types, but these types need to implement the IResettable interface. I defined the IResettable interface so that it is possible to call Reset() on the object that is returned.

You might have noticed that the pool doesn’t store objects of type <T> directly, but actually uses a wrapper class PooledObject<T>.

PooledObject.cs

    public class PooledObject<T> : IDisposable where T : IResettable
    {
        // -----------------------------------------------------------------
        // Data
        // -----------------------------------------------------------------
        private ConcurrentPool<T> mConcurrentPool;
        private readonly T mPooledObject;

        // -----------------------------------------------------------------
        // Constructor
        // -----------------------------------------------------------------
        public PooledObject( T inOnbject, ConcurrentPool<T> inConcurrentPool )
        {
            mPooledObject = inOnbject;
            mConcurrentPool = inConcurrentPool ?? throw new Exception("[Pooled Object] Concurrent Pool is null");
        }

        // -----------------------------------------------------------------
        // IDisposable Interface
        // -----------------------------------------------------------------
        public void Dispose()
        {
            mPooledObject.Reset();
            mConcurrentPool.Return( this );   
        }

        // -----------------------------------------------------------------
        public T Value
        {
            get
            {
                return mPooledObject;
            }
        }
    }

The reason to use PooledObject is because I want to wrap T objects around an IDisposable object so that they can be automatically reset and returned to the pool when the object is disposed. By doing it this way, I won’t have to worry about calling ConcurrentPool.Return explicitly after I’m done using the object. It will also result in very clean code since it is possible to take advantage of the using statement – which expects the IDisposable interface – which in turn disposes of the object as soon as the execution goes out of its scope.

Usage

            ConcurrentPool<DummyClass> pool = new ConcurrentPool<DummyClass>( () => new DummyClass() );

            Parallel.For( 0, 10000, ( index ) =>
            {
                using( PooledObject<DummyClass> DummyClass = pool.Get() )
                {
                    ProcessDummy( DummyClass.Value );
                }
            }
            );

Conclusions

We have looked at what an Object pool is and what its advantages are. We also discussed what happens when multi-threading is introduced and how we can solve race conditions using a lock or concurrent collections. We also looked at how to use the IDisposable interface to return pooled objects automatically.

An intersting exercises could be the use of all the different concurrent collections available and check for any perfomance differences.

Find my on my Github here: https://github.com/lormori/design-patterns

References

https://devblogs.microsoft.com/pfxteam/faq-are-all-of-the-new-concurrent-collections-lock-free/
https://stackoverflow.com/questions/4228864/does-lock-guarantee-acquired-in-order-requested


Back in the day when I started Uni, I had no idea what Version Control was. So, when tasked to choose my repository I just picked up what a friend of mine recommended. I then installed TortoiseHG on my Windows machine, created a BitBucket account and there I was, using Mercurial as my repository of choice.

I then realised that many many many many people use Github to share code and work on open source projects. Also, I discovered Github does not use Mercurial but uses Git as their distributed version control system.

For this reason I decided to try Git and learn how it works. My very first question was: how can I move Mercurial repositories into Git? I could just copy/paste the projects in the state they are and create a brand new Git repository with them. But what if… what if I wanted to move them to Git and keep all the previous changelists. How do I do it? Let me show you.

Prerequisite – Install Git and TortoiseHG (Windows)

First, I had to install Git (of course!) You can follow this link that has a super useful guide to do so and it’ll tell you all you need to know. Next install TortoiseHG from here: I use it as a Mercurial client but it also has a neat and useful extension which we are going to use to convert Hg to Git, called hggit.

Once everything is installed there are a few extra steps before the convertion.

Enable hggit in TortoiseHG

Open TortoiseHG workbench, go to File -> Settings and the Extension tab: select hggit.

Now that is enabled, we need to add a few extra settings to our mercurial settings file. This file is usually found in C:\Users\YOUR_USER\mercurial.ini

Add the following to the file:

hgext.bookmarks =

[git]
intree = True

Convert Mercurial to Git

In order to do the conversion you’ll need to open your Powershell / Command Prompt, navigate to your mercurial repository and then execute in order:

hg bookmark -r default master
hg gexport --debug

This creates a git bare repository. Bare repositories are generally used for sharing purposes, so what you need is a working directory instead: that is where you will be able to do ‘commit’ and ‘push’ onto your repository. To do this, you have to set the bare flag of your repository to false and reset the repository to start fresh (still in Powershell or Command Prompt):

git config --bool core.bare false
git reset HEAD -- .

Almost there! your folder structure should look like this

You can delete the .hg folder and there you have a git repository.

You can check the status of your repository to make sure everything is in place:

PS D:\Dev\UnityChat&amp;gt; git status
On branch master
nothing to commit, working tree clean

If anything has gone wrong you can reset the repository with:

 hg gclear 

command.

Push your Git repository to Github

Go to your github account and create a new repository. You can do this by clicking the ‘+’ sign on your profile page.

Once the repository is created you can push your local repository on Github with:

PS D:\Dev\UnityChat&amp;gt; git remote add origin https://github.com/lormori/UnityChat.git
PS D:\Dev\UnityChat&amp;gt; git push -u origin master
Enumerating objects: 138, done.
Counting objects: 100% (138/138), done.
Delta compression using up to 4 threads.
Compressing objects: 100% (123/123), done.
Writing objects: 100% (138/138), 73.24 KiB | 1.46 MiB/s, done.
Total 138 (delta 80), reused 0 (delta 0)
remote: Resolving deltas: 100% (80/80), done.
To https://github.com/lormori/UnityChat.git
* [new branch] master -&amp;gt; master
Branch 'master' set up to track remote branch 'master' from 'origin'.

And there you have it, your whole project is now on Github with your previous ChangeLists. You can carry on working on it and ‘commit’ new stuff this way:

PS D:\Dev\UnityChat&amp;gt; git commit -a -m &quot;test commit&quot;
[master f78ecd0] test commit
1 file changed, 1 insertion(+), 1 deletion(-)
PS D:\Dev\UnityChat&amp;gt; git push
Enumerating objects: 11, done.
Counting objects: 100% (11/11), done.
Delta compression using up to 4 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (6/6), 483 bytes | 241.00 KiB/s, done.
Total 6 (delta 5), reused 0 (delta 0)
remote: Resolving deltas: 100% (5/5), completed with 5 local objects.
To https://github.com/lormori/UnityChat.git
3bdd378..f78ecd0 master -&amp;gt; master

Conclusion

It is relatively easy to convert a Mercurial repository to Git, if you wish to do so. Just install Git and TortoiseHG on your machine and you are closer than you think you are! Once it is all up and running, you can now use your Git repository with the command line, but there are a few visual clients you can use instead. You can just use TortoiseHG with the hggit extension enabled, or you could download SourceTree, which seems very good for the job. In the end, it is up to you which tools you prefer to use while working: what matters is to get the job done.

I hope you’ll find this useful, and just in case you want to have a look, you can check out my new shiny github repository that I created this way. It still contains all the old commits from the mercurial one!

References and further reading

https://helgeklein.com/blog/2015/06/converting-mercurial-repositories-to-git-on-windows/ – Major article I followed
https://www.sourcetreeapp.com/ – Cool visual client which I might adopt
http://www.saintsjd.com/2011/01/what-is-a-bare-git-repository/
https://gist.github.com/seankross/8830032
https://stackoverflow.com/questions/11656761/git-please-tell-me-who-you-are-error
https://gitforwindows.org/
https://help.github.com/articles/create-a-repo/
http://www.rockstarprogrammer.org/post/2008/apr/06/differences-between-mercurial-and-git/
https://importantshock.wordpress.com/2008/08/07/git-vs-mercurial/
https://ericsink.com/entries/hg_denzel.html

Python seems to be the new thing. Everyone talks about it, everyone seems to appreciate it.
So I decided to give it a go, and started studying it.
I found out that it is extremely simple and easy to get along with.
I’ve been working with C# for mostly of my last two years, and I have to say, learning a new language is a really good challenge for me.
It felt like something fresh, and I really enjoy this new beast. I still have to get my head around it as like what are the best practices to write good python code. But still, I really like it.
I followed a series from the Google Developers channel on youtube and I highly recommend this series because it is really easy and clear, especially for new comers like me. I mean, at the end of the lectures, I was able read an Apache file to gather information about sliced images that I had to download from the web. Download these images, save them to a folder and put them back together in an html file to get the final image. Isn’t that awesome?
Here are the links of the first two lectures for each of the two days. Have a look! I believe this is really good stuff.

Google Python Class Day 1 Part 1

Google Python Class Day 2 Part 1

I finally managed to finish my website. At least for now. I feel quite proud with it, since it is the very first time that I spent some time on it and I really work hard to make it happen. It’s no completely finished, but I wanted to put it online to share it with everyone, to gather comments and know what people think about it.

I’m currently using WordPress as a CMS and what I did was to create a brand new theme for it from scratch. I started with Bootstrap, in this way I was able to have a responsive website in just few steps.

I then followed this tutorial to create a responsive theme for WordPress with Bootstrap.

After that the hard part was to give this website a style. I’m not a designer so this has been a real challenge. I went for a flat design since this seems to be the trend nowadays and this is the final result. I will keep changing and modifying it, but I wanted to have it real and clear right at the beginning of the new year!

For those interested, you can find the source code for this website on my Github. Feel free to have a look, download and modify it how you like it! =)

Happy New Year!

Finally, after struggling a lot with the maze generation algorithm for my Creative Coding module at Goldsmiths, I managed to implement it and have it working properly. I redesigned it completely because there were different errors in the previous version and it was faster to start it again from scratch then check the code over and over again.
So, after 1600 lines of code, the cubeMaze generator is ready to be used to create the final labyrinth mesh for our iPhone game!

Here is a snapshot from one of my teammates work, which shows the mesh generator ready to get my data!

cubic maze

For my first assignment of the Workshop in Creative Coding at Goldsmiths we have to utilize OpenFrameworks to create an iOS mobile application.
It is a group project, and one of my team mates came up with an idea base on my maze generator that I implemented for my Intro to Game Programming Assignment.

The idea is basically to riproduce my maze generation algorithm on the surface of a cube. So in these two days I went crazy trying to provide the right algorithm that will be used to produce the final labyrinth mesh. After struggling for ages because of the thousands more controls that I need to do, I finally managed to get something acceptable. Here are my results coming just from the console.

Every face is printed one by one, the E character represent the wall, and where there is nothing it means that there is… nothing! The player will be able to move between the empty space… I hope.

ofMaze