OK, Singleton in Java.

Fine, this topic has been talked many many times, and you can find a lot of great answers over the internet. Stackoverflow.com listed a lot of answers. And also, you can find great approach from Joshua Bloch’s Effective Java also pointed out 2 effective approaches. What’s more, Joshua Bloch also provided an enum approach(Page 31) as the best practice for Serializable Singleton. If you like Wikipedia, you can also find a Java solution for Singleton, and for deep background knowledge behind this approach, please read “Double check locking” and “Java 5 memory management” by Bill Pugh.

If you are as lazy as me, just remember the following implementation, which is thread safe and can be used on all the java version. The key point in this implementation is using Java atomic class load mechanism to guarantee the thread safe and using static method to implement lazy initialization.

If you also have some curious on the other implementations, please keep reading.

  1. The simplest implementation(Immutable class, thread safe, but no lazy initialization)
  2. The double check locking implementation(Thread safe, lazy initialization, but requires Java 5+)
  3. The enum implementation(Thread safe, Serializable, also requires Java 5+)

After reading all of these, I don’t think you need any other implementations, but to understand why and how these implementations work, you need read something more[Typically those links I provided at the beginning]. There are things called Google and Bing on the earth, I guess you can find the answer very soon.

Funny problem: How fast can you reverse a string in Java and C#?

I saw an interview question.

Write a function to reverse a string.

It’s a simple question, Hmm? But not so simple.

In Java, StringBuilder class provided a convenient method to reverse the characters it holds, and in C#, we have a static method Array.reverse() to help us. Also, we can write it by ourselves(it’s not a big deal, right?).

OK, let’s take a look at how we can do this.

It’s simple. Hmm? We turn the string into char array, and swap the array element. It’s done.

If we use the API provided by .NET Framework, it will be much more simple.

These 2 approaches are all right, and we can reverse an alphabet string and also, we can reverse an Unicode string like “私は中国人です。”. But if we need to reverse 10,000 strings and each string was 10,000 characters long, which one could be faster?

Continue reading