I wrote a below Singleton class. I am not sure whether this is thread safe singleton class or not?
public class CassandraAstyanaxConnection {
private static CassandraAstyanaxConnection _instance;
private AstyanaxContext<Keyspace> context;
private Keyspace keyspace;
private ColumnFamily<String, String> emp_cf;
public static synchronized CassandraAstyanaxConnection getInstance() {
if (_instance == null) {
_instance = new CassandraAstyanaxConnection();
}
return _instance;
}
/**
* Creating Cassandra connection using Astyanax client
*
*/
private CassandraAstyanaxConnection() {
context = new AstyanaxContext.Builder()
.forCluster(ModelConstants.CLUSTER)
.forKeyspace(ModelConstants.KEYSPACE)
.withAstyanaxConfiguration(new AstyanaxConfigurationImpl()
.setDiscoveryType(NodeDiscoveryType.RING_DESCRIBE)
)
.withConnectionPoolConfiguration(new ConnectionPoolConfigurationImpl("MyConnectionPool")
.setPort(9160)
.setMaxConnsPerHost(1)
.setSeeds("127.0.0.1:9160")
)
.withAstyanaxConfiguration(new AstyanaxConfigurationImpl()
.setCqlVersion("3.0.0")
.setTargetCassandraVersion("1.2"))
.withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
.buildKeyspace(ThriftFamilyFactory.getInstance());
context.start();
keyspace = context.getEntity();
emp_cf = ColumnFamily.newColumnFamily(
ModelConstants.COLUMN_FAMILY,
StringSerializer.get(),
StringSerializer.get());
}
/**
* returns the keyspace
*
* #return
*/
public Keyspace getKeyspace() {
return keyspace;
}
public ColumnFamily<String, String> getEmp_cf() {
return emp_cf;
}
}
Can anyone help me with this? Any thoughts on my above Singleton class will be of great help.
Updated Code:-
I am trying to incorporate Bohemian suggestion in my code. Here is the updated code, I got-
public class CassandraAstyanaxConnection {
private static class ConnectionHolder {
static final CassandraAstyanaxConnection connection = new CassandraAstyanaxConnection();
}
public static CassandraAstyanaxConnection getInstance() {
return ConnectionHolder.connection;
}
/**
* Creating Cassandra connection using Astyanax client
*
*/
private CassandraAstyanaxConnection() {
context = new AstyanaxContext.Builder()
.forCluster(ModelConstants.CLUSTER)
.forKeyspace(ModelConstants.KEYSPACE)
.withAstyanaxConfiguration(new AstyanaxConfigurationImpl()
.setDiscoveryType(NodeDiscoveryType.RING_DESCRIBE)
)
.withConnectionPoolConfiguration(new ConnectionPoolConfigurationImpl("MyConnectionPool")
.setPort(9160)
.setMaxConnsPerHost(1)
.setSeeds("127.0.0.1:9160")
)
.withAstyanaxConfiguration(new AstyanaxConfigurationImpl()
.setCqlVersion("3.0.0")
.setTargetCassandraVersion("1.2"))
.withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
.buildKeyspace(ThriftFamilyFactory.getInstance());
context.start();
keyspace = context.getEntity();
emp_cf = ColumnFamily.newColumnFamily(
ModelConstants.COLUMN_FAMILY,
StringSerializer.get(),
StringSerializer.get());
}
/**
* returns the keyspace
*
* #return
*/
public Keyspace getKeyspace() {
return keyspace;
}
public ColumnFamily<String, String> getEmp_cf() {
return emp_cf;
}
}
Can anyone take a look and let me know if this time I got it right or not?
Thanks for the help.
You are implementing the lazy initialization pattern - where the instance is created when first used.
But there is a simple trick that allows you to code a threadsafe implementation that doesn't require synchronization! It is known as the Initialization-on-demand holder idiom, and it looks like this:
public class CassandraAstyanaxConnection {
private CassandraAstyanaxConnection(){ }
private static class Holder {
private static final CassandraAstyanaxConnection INSTANCE = new CassandraAstyanaxConnection();
}
public static CassandraAstyanaxConnection getInstance() {
return Holder.INSTANCE;
}
// rest of class omitted
}
This code initializes the instance on the first calling of getInstance(), and importantly doesn't need synchronization because of the contract of the class loader:
the class loader loads classes when they are first accessed (in this case Holder's only access is within the getInstance() method)
when a class is loaded, and before anyone can use it, all static initializers are guaranteed to be executed (that's when Holder's static block fires)
the class loader has its own synchronization built right in that make the above two points guaranteed to be threadsafe
It's a neat little trick that I use whenever I need lazy initialization. You also get the bonus of a final instance, even though it's created lazily. Also note how clean and simple the code is.
Edit: You should set all constructors as private or protected. Setting and empty private constructor will do the work
all above methods are eagerly initializing object. how about this. This will help you to initialize ur class lazily. You may have heavy object and you don't want to initialize on startup.
public class MySinglton {
private MySinglton (){}
private static volatile MySinglton s;
public static MySinglton getInstance(){
if (s != null ) return s;
synchronized(MySinglton.class){
if (s == null ) {
s = new MySinglton();
}
}
return s;
}
}
As mentiond in this great article here :
The best solution to this problem is [...] to use a static field
public class Singelton {
private static final Singelton singleObject = new Singelton();
public Singelton getInstance(){
return singleObject;
}
}
No, its not thread-safe if the values returned on the pulbic methods are changeble objects.
To this class be Thread-safe one way is to change it to be immutable.
To do that, you could change this methods like this:
public Keyspace getKeyspace() {
// make a copy to prevent external user to modified or ensure that Keyspace is immutable, in that case, you don't have to make a copy
return new Keyspace( keyspace );
}
public ColumnFamily<String, String> getEmp_cf() {
// Same principle here. If ColumnFamily is immutable, you don't have to make a copy. If its not, then make a copy
return new ColumnFamily( emp_cf );
}
In this book Java Concurrency in Practice you can see the principle of that immutability.
No, this does not appear to be thread-safe. It appears that you there is mutable data accessible after the call to getInstance, where the lock would have been released.
This should be the correct way to implement Singleton pattern using double checked locking principle:
class MySinglton {
private static volatile MySinglton instance;
private MySinglton() {}
public static MySinglton getInstance() {
if (instance == null) {
synchronized (MySinglton.class) {
if (instance == null) {
instance = new MySinglton();
}
}
}
return instance;
}
}
I think this will do the same thing without having to check for instance every time. static is the same as check first time
public class Singl {
private static Singl _instance;
//other vars
static{
//synchronized(Singl.class){//do not need
_instance = new Singl();
//}
}
public static Singl getInstance() {
return _instance;
}
private Singl(){
//initizlize
}
}
After java 1.5 version we can use volatile. If we used volatile java key ward, we can create singlton class with thread safe, Because instance variable share with Other thread as well.
public class SingleWithThreadSafe {
// create an object static referance of SingleWithThreadSafe with volatile
private static volatile SingleWithThreadSafe instance = null;
// if we make the constructor private so that this class cannot be
// instantiated from out side of class
private SingleWithThreadSafe() {
}
// Get only object available
public static SingleWithThreadSafe getInstance() {
if (instance == null) {
instance = new SingleWithThreadSafe();
}
return instance;
}
public void showMessage() {
System.out.println("Hello World!");
}
}
Related
Singleton class
public class M_Singleton{
private volatile static M_Singleton uniqueInstance=null;
private ArraList<Integer> myArr;
private M_Signleton{
this.myArr=new ArrayList<Integer>();
}
public static M_Singleton getInstance(){
if(uniqueInstance==null){
synchronized (M_Signleton.class){
if(uniqueInstance==null)
uniqueInstance=new M_Signleton();
}
}
return uniqueInstance;
}
public void deleteInstance(){
uniqueInstance=null;
}
}
Main class
M_Singleton ms=M_Singleton getInstance();
//put A-value in "MyArr"
sd.deleteInstance();
//put B-value in "MyArr"
I thought, there would be only B-value in MyArr
But there is only A-value.
If I change deleteInstance like this, there is only A-value still.
public void deleteInstance(){
uniqueInstance=new M_Singleton();
}
How to destroy singleton?
make singleton object null for destroy singleton like this
uniqueInstance=null
If you really want to stick to Singleton for your case, below is a Java reflection way for resetting your single instance:
public static void setPrivateField(Class clazz, Object inst, String field, Object value) throws Exception {
java.lang.reflect.Field f = clazz.getDeclaredField(field);
f.setAccessible(true);
f.set(inst, value);
f.setAccessible(false);
}
Just call this method like below wherever you need to reset this singleton:
setPrivateField(M_Singleton.class, null, "uniqueInstance", null);
I am new to Java and started learning and exploring bit about language. Could anyone explain what is significance of _() in that constructor. Is that called constructor?
public class UserRequestCache {
private final static ThreadLocal <UserRequest> t = new ThreadLocal <UserRequest>();
private static UserRequestCache instance = new UserRequestCache();
public static UserRequestCache _() {
return instance;
}
private UserRequestCache() {
}
public void checkPoint() {
if (logDebug()) {
if (getUserRequest() != null) {
logDebug(getUserRequest().toString());
}
}
}
public UserRequest getCache() {
// checkPoint();
return getUserRequest();
}
private UserRequest getUserRequest() {
return t.get();
}
public void setCache(UserRequest value) {
t.set(value);
}
}
No, it's just a very poorly named method. I recall another similar question recently, that quoted some documentation saying that even though a single underscore is a legal name, it shouldn't be used.
In this case it seems that the class is a Singleton, and the method that's usually named getInstance() has been shortened to _().
It's a funny construct that you have here. the name of the function is '_'.
So you have something like UserRequestCache._() that return a UserRequestCache.
Nothing to do with some weird Java 'magic'
Here is my code.
public class PropertyLoader {
private Properties appProperties;
/**
* The instance.
*/
private static PropertyLoader inst = null;
/**
* Instantiates a new property data loader.
*/
private PropertyLoader() {
try
{
appProperties = new Properties();
appProperties.load(this.getClass().getClassLoader().getResourceAsStream("app.properties"));
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static PropertyLoader getInstance() {
if (inst == null) {
inst = new PropertyLoader();
}
return inst;
}
}
public String getPropertyAPP(String key) {
return appProperties.getProperty(key);
}
}
Synchronization is needed for the getPropertyAPP method: it is a singleton, so many threads can access the same instance simultaneously and call it.
Can anyone suggest me the right way?
you can use following solution
public class PropertyLoader {
private Properties appProperties;
/** The instance. */
private static PropertyLoader inst = null;
static{
inst = new PropertyLoader();
}
/**
* Instantiates a new property data loader.
*/
private PropertyLoader() {
try
{
appProperties = new Properties();
appProperties.load(this.getClass().getClassLoader().getResourceAsStream("app.properties"));
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static PropertyLoader getInstance() {
return inst;
}
public String getPropertyAPP(String key) {
return appProperties.getProperty(key);
}
}
A simpler solution, which is also thread safe, is to use static initialisation to initialise a static field.
public class AppProperties {
private static final Properties appProperties;
static {
try {
appProperties = new Properties();
appProperties.load(AppProperties.class
.getClassLoader().getResourceAsStream("app.properties"));
} catch(IOException e) {
e.printStackTrace();
}
}
public String get(String key) {
return appProperties.getProperty(key);
}
public String get(String key, String defaultValue) {
return appProperties.getProperty(key, defaultValue);
}
}
You have a massive race condition happening in your getInstance() method. If more than one threads call getInstance() at the same time you will create multiple instances and assign them in turn to the static variable. Considering what you're doing here this won't cause any logic problems, but does mean you're doing more work than necessary.
I recommend you do some reading about the Singleton pattern, why it's bad, and how to implement it in a safe way in Java.
But in short, don't use the Singleton pattern, it's hideously broken and will make any code that uses this object tightly-coupled and will inhibit your ability to do any kind of isolated testing.
Several issues with your code:
(a) Are you sure you need lazy initialisation? The cost of initialisation must be noticeable and the chance that the resource is never used must be non-zero. Also: it may be preferable to fail during program start rather than at some indeterminate moment later when the resource is first accessed. This really depends on your application.
(b) One way of implementing the lazy initialisation is using the correct version of double checked locking (the volatile keyword is essential):
private static volatile PropertyLoader inst;
...
public static PropertyLoader getInstance() {
if (inst == null) {
synchronized(PropertyLoader.class) {
if (inst == null) {
inst = new PropertyLoader();
}
}
}
return inst;
}
This wikipedia article explains why this works (as of Java 5 but nore before): http://en.wikipedia.org/wiki/Double-checked_locking
(c) Catching exceptions and simply logging them is plain wrong under most circumstances. In your case, no property would ever be returned from getPropertyAPP. This may be ok if the presence of the properties is clearly declared to be optional.
See this incomplete code fragment:
public class Singleton implements Serializable {
private static class SingletonHolder {
private static final Singleton SINGLETON_INSTANCE;
static {
Singleton tmp = singletonTMP;
if (tmp != null) {
SINGLETON_INSTANCE = tmp;
} else {
// etc.
}
}
}
private static volatile Singleton singletonTMP;
// etc.
}
I get a strange warning in NetBeans at line Singleton tmp = singletonTMP;: "Usage of static non-final variable used during initialization".
So, yes. This is true, of course, but why would this be a problem?
The problem is that the variable :
private static final Singleton SINGLETON_INSTANCE;
might not have been initialized in that static block of yours, you can inititalize it to null(say) in the else clause inside that static block, i.e:
static
{
Singleton tmp = singletonTMP;
if (tmp != null)
{
SINGLETON_INSTANCE = tmp;
} else
{
**SINGLETON_INSTANCE = null;**
}
}
After reading a bit about security I think my previous comment was correct.
I think it is a security issue, an attacker could replace your static field with a new object. This happens when the attribute is also defined as public. I assume netbeans considers it a risk and displays the warning even if you declared it private.
More details here:
https://www.securecoding.cert.org/confluence/display/java/OBJ10-J.+Do+not+use+public+static+nonfinal+variables
I have encountered a weird problem in my app (java).
I have an enum. Something like that
public enum myEnum implement myIntrface{
valueA(1),valueb(2),valuec(3),valued(4)
private int i;
// and then - a constructor
public MyEnum(int number){
i = number;
}
private MyObj obj = new MyObj;
// getter and setter for obj
}
and in another class I have this
MyEnum.valueA.setObj(new Obj(...))
in briefe - I have an enum with a private instance member that has a set and a get.
So far so good -
The only thing that amazes me is that later on I look at the value of the MyEnum.valueA().obj is null.
there is nothing that updates the value to null, I have even gave it a default value in the constructor and I still see it null later.
any suggestions?
Enums should be un-modifiable classes so you shouldn't really be doing this. If your looking to modify the state of a type based object like an enum you should use an final class approach with embedded constants. Below is an example of a class based approach with a modifiable name an a un-modifiable name...
public final class Connection {
public static final Connection EMAIL = new Connection("email");
public static final Connection PHONE = new Connection("phone");
public static final Connection FAX = new Connection("fax");
/**/
private final String unmodifiableName; //<-- it's final
private String modifiableName;
/*
* The constructor is private so no new connections can be created outside.
*/
private Connection(String name) {
this.unmodifiableName = name;
}
public String getUnmodifiableName() {
return unmodifiableName;
}
public String getModifiableName() {
return modifiableName;
}
public void setModifiableName(String modifiableName) {
this.modifiableName = modifiableName;
}
}
The purpose of enums is to represent constant values. It does not make any sense to set the fields of a constant value.
You should declare your fields as final, and use the constructor to initialize all of them.
For reference, the following code works as expected:
public class Test {
public static enum MyEnum {
valueA(1),valueb(2),valuec(3),valued(4);
private int i;
private Object o;
private MyEnum(int number) {
i = number;
}
public void set(Object o) {
this.o = o;
}
public Object get() {
return o;
}
}
public static void main(String[] args) {
System.out.println(MyEnum.valueA.get()); // prints "null"
MyEnum.valueA.set(new Integer(42));
System.out.println(MyEnum.valueA.get()); // prints "42"
}
}
the cause of this problem is the db40 framework . It loads an enum from the db using reflection. This is well documented .
http://developer.db4o.com/Forums/tabid/98/aft/5439/Default.aspx