Skip to main content

Posts

Showing posts with the label Singleton

What is Singleton Pattern?

The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object Singletons (being often a bad choice) are classes that can have only one instance throughout the whole program. For example a SingletonConfigFile might look like this. It is for reading one file only. It would make sense for this to be a config file. If your class can be instantiated more than once, for different files, it is not singleton. Don't use this code - it doesn't take into account concurrency problems which are a whole different area of discussion.    public SingletonConfigFile {    private static String filename = "config.xml";    private File file;    private static SingletonConfigFile instance;

per-thread Singleton and per-thread Logging in Java

Usage of ThreadLocal : per-thread Singleton and per-thread Logging Should you require a refresh of what ThreadLocal s in Java are and how they work, refer to this article first. You can then proceed with the current article for understanding two of the most common uses of ThreadLocal s in Java. per-thread Singleton impl using ThreadLocal Suppose you have a need of having a JDBC Connection objects per thread of your application. The moment you hear the term 'per-thread', ThreadLocal automatically comes into mind as that's what it's primarily meant for. Below is a sample implementation of how easily can you actually use ThreadLocal for a per-thread JDBC Connection object in Java.