Bloomberg LP Interview Question
Country: United States
// Something.h
#include <mutex>
class Something
{
public:
static Something *singleton()
{
if (!val)
std::call_once(val_flag, singleton_once);
return val;
}
private:
Something();
static Something *val;
static std::once_flag val_flag;
static void singleton_once()
{
static Something ret;
val = &ret;
}
};
//Something.cpp
Something *Something::val = NULL;
std::once_flag Something::val_flag;
Also, to add up, according to C++11 static declarations are thread safe, no need for call_once there... and call_once is C++11 feature :)
package com.doubble.checked.singleton;
public class DoubleCheckedSingleton {
public static void main(String[] args) {
MySingleton instnace = MySingleton.getInstance();
System.out.println(" "+instnace.hashCode());
instnace = MySingleton.getInstance();
System.out.println(" "+instnace.hashCode());
}
}
class MySingleton {
private static volatile MySingleton instance;
private MySingleton() {
// TODO Auto-generated constructor stub
}
//double locking check
public static MySingleton getInstance(){
if(instance==null) // 1st locking check without threading
synchronized (MySingleton.class) {
if(instance==null) // 2nd locking check with threading
instance = new MySingleton();
}
return instance;
}
}
search for 1008019 at stackoverflow. Make sure you click all the links in the article, it is quite a bit of information, but worth reading. I sent you c++ article because I think Bloomberg prefers c++ over other languages
- animageofmine June 08, 2015