Using Multithreaded Counters Safely

Have you ever had multiple threads running all trying to read and update a counter variable? Has that variable not always been what you expected? If yes you are probably not using any type of locking to guard that variable from being updated in one thread at the exact same time another thread is trying to update it as well. There are two main ways of updating a counter variable safely and ensuring that a value does not get missed or overwritten in C#. Those two ways are using the lock keyword or using the Interlocked class in .Net.

Keep in mind that incrementing  involves three actions:

  • Read, in which a variable is accessed from memory.
  • Increment, in which the value is increased.
  • Write, where the incremented value is written back to memory.

If multiple threads are trying to do this all at once there can be trouble. If thread A is in the increment step at the same time thread B is at the read step, then when A writes its value B will overwrite it with the exact same value. Two increments will only be seen as one in this scenario.

Lock

The first way is to have some code such as the following:

object myLock = new object();
int counter = 0;
        
public void ThreadMethod()
{
        lock(myLock)
    {
        counter++;
    }
}

Here we create an object, myLock, which is the object we are going to lock on, this is like the bathroom key at a gas station, only the current holder of the key can use the bathroom at that given time. The counter variable will hold the current count. We have a method, ThreadMethod, which is going to be run by multiple threads all at once, pretend some actual work gets done in there as well. Inside this method we “lock” on the myLock object which means only one thread is allowed inside the lock block at any given moment. As soon as one thread exists the lock block, another thread may enter. This insures that only a single thread is able to increment the counter variable at a time.

This method works fine but there are a few things to consider.

  • Using a lock is slow because only one thread can be inside the lock at once.
  • You have to remember to use the lock everywhere the variable is accessed.
  • If the lock object is reused for other variables they will all wait on the unrelated operations. Use a new lock object per variable.
  • Lock is great if you are doing more than just incrementing a variable and the code inside is more complex.

Interlocked

System.Threading.Interlocked is a faster alternative to the previous use of lock. It is good for incrementing and decrementing a counter and not for more complex locking situations.

int counter = 0;
        
public void ThreadMethod()
{
    Interlocked.Increment(ref counter);
}

This sample is doing the same thing as the lock sample, only now it is does not need the lock object. Here the Interlocked.Increment method takes a reference to the counter variable and increments it in a single, atomic CPU instruction. That means that the read, increment, and write are being done all at once and therefore multiple threads will not step on each other when trying to increment the counter variable. Since this is an atomic operation there is no possibility of a context switch during the increment.

I was curios as to how this was being done so I found the .Net code on github. All the related methods for incrementing boiled down to this:

internal static extern int ExchangeAdd(ref int location1, int value);

That is helpful isn’t it? I had never seen the extern keyword before and this ExchangeAdd method is just declared, with no body. After a little research I found a few things out. According to the C# specification 10.6.7 (word doc):

When a method declaration includes an extern modifier, that method is said to be an external method. External methods are implemented externally, typically using a language other than C#. Because an external method declaration provides no actual implementation, the method-body of an external method simply consists of a semicolon. An external method may not be generic. The extern modifier is typically used in conjunction with a DllImport attribute, allowing external methods to be implemented by DLLs (Dynamic Link Libraries). The execution environment may support other mechanisms whereby implementations of external methods can be provided. When an external method includes a DllImport attribute, the method declaration must also include a static modifier.

So the extern keyword simply means the method is written in unmanaged code and gets filled in by the compiler. This can allow for lower level code to be used, in this case it boils down to one cpu instruction.

Summary

Both methods help keep our counters with the correct value and allow many threads to read, increment, and write all at nearly the same instant. Lock works for this case, but in more complex scenarios where more code is need lock really shines. Using the Interlocked class is much faster and cleaner when doing simple increment and decrement operations on a counter variable.

Let me know your thoughts and experiences with multithread counters, in the comments or on twitter @ScottKerlagon!

Recruiters, the Good the Bad and the Ugly

My Experience with Recruiters

I recently, for the first time, got a new job through a recruiter, who found me on LinkedIn. I have worked with several different recruiters over the past years with a wide range of results. While I can’t say I worked extensively with all of them, I have gone on several interviews through several different recruiting agencies. I would like to share some of my insights and help you understand how I perceive them to work. Now when I speak about recruiters, I am going to generalize and my opinions are only a reflection of the recruiters I have worked with. There have been some great ones and some horrible ones.

The Ugly

  • They will use you: Some use you to get their client more options when they have no interest in actually placing you and really want to place someone else. This can happen when a company says they need to interview x number of people before making a decision.
  • Not keeping you updated: Some recruiters are really bad at keeping you informed about interview results and positions they have mentioned. A lot of this will stem from my other points. Recruiters can turn unprofessional in a heart beat if they think you are no longer a viable option at the moment. Remember this and do not let it happen again when they call back a few months later begging you to go on another interview.
  • Quality vs quantity: Most recruiters are playing the numbers game. Get as many candidates in front of as many companies and they are bound to get a commission. The problem is they may not always care about the perfect fit and just be looking for any fit.

The Bad

  • What kind of companies use recruiters: I get the feeling, often, and this is probably not always true, but the companies that need to use a recruiter may have one of two problems.
    • The company may be unable to attract talent on their own.
    • The company may have recently had many people leave in a short amount of time.

    Both of these problems should have you asking a lot of questions.

  • Get you a less than perfect job: The recruiters have many openings that they are trying to fill. You are a candidate that could possibly fit. They will try to jam a square peg into a round whole if the position has been open for too long. Just refer to my tip below on being specific.
  • Who pays the recruiter: In my experience the hiring company pays the recruiter a percentage of your starting salary. While this seems to work in your favor it doesn’t always get you the best offer. A recruiter is more interested in a middle ground offer, rather than risk losing the commission altogether. From the book Freakanomicsthe incentives of a real estate agent are shown not to align with a seller’s best interests. The same applies when working with a recruiter.

 

The Good

  • Large network: Recruiters have many contacts and clients and can get you in front of a lot of different companies. Often you can tell them what company you want to work for and they will help market you to them.
  • Interview advice: They can and often will give you advice throughout the interview process. From interview questions, what the company is looking for in a candidate, and things to avoid. This advice is invaluable and will help guide you in your discussions with the company. This information is perfect for narrowing your research on the company and what to brush up on.
  • Keep you informed: They will often keep you updated throughout the hiring process. Whether you are doing well or terrible, they will let you know how you did and any feedback from the company.
  • Negotiating help: They will act as a middleman while negotiating your salary and benefits. They will help filter out stupid statements you may make and answer questions more openly on possible scenarios. Most people fear having to negotiate a salary, I know I do, but the recruiter helps take that awkwardness out of it. A recruiter is not going to tell the company something that is going to hurt your chances. Just remember a little bit of negotiation is with the recruiter as well.

Tips

  • Be specific: In talking with your recruiter, be very specific in what you want in your next job. The better they understand you the better they will be able to find a good fit.
  • Practice interviews: You can use recruiters to get practice interviews. This is especially a good idea if you are rusty or not good at interviewing. Now obviously don’t tell the recruiter you aren’t serious about the particular interview, but who knows you may end up actually wanting the job. So if you are rusty take an interview that you are not completely excited about just to get in a little more interviewing experience.
  • Interview when you don’t need a job: The best time to interview is when you don’t need a job. This gives you time to find a perfect fit as well as being the ultimate leverage when it comes time to negotiating your salary.
  • Don’t give out your current salary info: Never tell the recruiter what you are currently making. Tell the recruiter you want a fair rate that matches the job in question and that your current and past salaries have nothing to do with what you are applying for. The only possible time you may consider telling a recruiter what you currently make, is if you get an offer lower than your current salary and you really, really want that job for whatever none money reasons their may be. In all other circumstances giving out your current or past salary information can only hurt you.
  • Recruiter interview: Most recruiters will want some kind of face time with you before they send you on interviews. This is so they can tell their client they have screened everyone of their candidates and also so they can grade you as well. All recruiters will grade you on their first impression of you on things like perceived intelligence, appearance, and other qualities. Based on this grading they will assign you an overall value and place you in their database. If this grade is low you will probably never hear from them again. Recruiters work from the top of that list as those candidates are more likely to get them a commission. So take this interview seriously!
  • Don’t waste your own time: If you feel a recruiter doesn’t have your best interests in mind and is being unprofessional in any way, stop working with that one. There are so many recruiters out there, just pick a better one, they exist!

Conclusion

Recruiters are a great way to get interviews and handle a lot of the dirty work in the job process, from finding open positions, company research, and negotiating salary. While using a recruiter may not be the best solution to landing a new job it is certainly a viable option. The best way to getting a job is through a referral from your personal network. Just remember a recruiter has their own best interests in mind and those interests may or may not always align with yours!

Let me know about your experiences with recruiters, good and bad, in the comments or on twitter @ScottKerlagon!

Improve Your Code by Using the New C# 6 Features

The new versions, C# 6 and Visual Studio 2015 come with some pretty cool new features. Mads Torgersen and Dustin Campbell gave a presentation at //build/ 2015 covering a lot of them, which can be viewed at https://channel9.msdn.com/Events/Build/2015/3-711. I want to point out and give a few samples of the ones I found the most interesting and useful.

IDE Features

Many new features have been added in Visual Studio 2015. They are mostly subtle, but they each make life just a little bit easier.

Fade Unused Code

Now, for example, in your list of using statements at the top of each file the unused ones become faded to tell you that your code is not actually using anything from those namespaces. As you can see below the only using statement being referenced is the System namespace. All the rest are not used in this particular coding file and are faded out.

Faded Usings Feature

Quick Actions

As you might have noticed there is also a new little light bulb to the left of the code. This little guy means there are suggestions to make your code better. Clicking on it shows you something like the screenshot below. It is showing you that it can remove unused using statements and is indicated in the red highlighted area. These new suggestions are designed to keep you in the coding context without a jarring dialog that takes over your focus.

Visual Studio Light bulb Feature

Refactoring

Another cool enhancement is the rename functionality. As you type a new name the rename functionality keeps you in the code editor and shows you the changes live as you type.

Visual Studio Rename Feature

Naming conflicts are auto-resolved, if possible, by adding things like the this keyword in-front of the conflict.
If you create an inline temporary variable and then use it, lets say in the next line, Visual Studio can easily get rid of that variable and combine the two lines. This helps make your code shorter, easier to read and maintain.

C# 6 Language Features

There are also many cool little additions to the language that make code more readable and faster to create due to it’s compactness and brevity.

Import using static

By adding in the using declarations at the top of your code file, where your using statements are, you can add something like “using static System.Console;” This will allow you to write the below code.

Static Using Statement Feature

Here you can see that instead of prefixing your method call with the static class name, you can simply call the static method. Personally I am not sure if this makes the code more readable or not. The static keyword Console, in this case is telling you more about where that line is being written. However using it on something like Math.Abs(5.5) -> Abs(5.5) I would say is more readable and clearer. This ability can be used with Enums as well. I would advise caution when using this new feature and only use it when it actually makes the code more clear and not more confusing. I believe this will depend on how telling names of the class and method are.

Method Declarations

Often we have simple method declarations that are one line and need {‘s and return keywords, in other words, lots of boilerplate code. Now we can get rid of that boilerplate and rewrite the old code in one line using lambda style notation like below.

New Method Declaration Feature

Interpolated Strings and nameof()

This is my favorite new feature. It makes writing log messages and things like throwing exceptions on guard clauses so much easier. Interpolated Strings remove the old string.Format() and replace it with $”” and the place holders like {0} are replaced with {variable} and are not needed as the last parameters any more.

Interpolated Strings Feature

Here I combined the use of the new nameof() method to get the name of the property instead of using a hard coded string in the old way example. This becomes really useful when throwing ArgumentNullExceptions and you want to reference the parameter name. The old way would be a string and not get updated if the parameter name was refactored, now it is updated automatically.

Null Conditional

Perhaps the single most useful new feature is the Null Conditional. This helps remove all the null checking spaghetti code. The “Elvis” operator, “?.”, can now be leveraged to check nulls inline and check properties as you reference them.

Null Conditional Feature

As you see above, If I wanted to get the 3rd record from a list of people, I would have to check that the list is not null, that the list has an element at 3 and that the third element is not null. Instead of doing a bunch of comparisons count checking it can be simplified using the Elvis operator as show above. The way this new operator works is by returning the value if not null and a null value if any in the chain are null.

Conclusion

Using all these new features will help strip out and compact code. It helps eliminate boilerplate code, increase readability, maintainability, and contribute to the all around cleanness of the code. As I think Mads sums it up the best:

“Room for more logic on your screen.” -Mads

A full list of the features Mads covers in the talk can be found here http://blogs.msdn.com/b/csharpfaq/archive/2014/11/20/new-features-in-c-6.aspx (note the notes at the end of his post for changes). An interesting list of proposed changes for C# 7 (future) can be found on GitHub https://github.com/dotnet/roslyn/issues/2136 and is worth a glance.

Let me know in the comments or on twitter @ScottKerlagon how you think these new features will help improve your code!

Tagged