Per thread singleton pattern - java

In my work I stumbled upon such a design issue:
I need one instance of a Manager class per thread
These instances should be globally accessible, like in the singleton pattern via a static function
Each thread might need to initialize its instance with different arguments
The lifetime of these instances should be controllable, sometimes it would be beneficiary to remove an instance and allow GC to collect it
The first two points would make it a 'per thread singleton' if such a thing exists.
This is what I came up with (the code is simplified, I've omitted safety checks and so on):
public class Manager {
private final static ThreadLocal<Manager> local = new ThreadLocal<Manager>();
private int x;
Manager(int argument) { x = argument; }
public static void start(int argument) { local.set(new Manager(argument); }
public static void clean() { local.remove(); }
private void doSomething1() { x++; .... }
private int doSomething2() { if (--x == 0) clean(); ... }
public static void function1() { local.get().doSomething1(); }
public static int function2() { return local.get().doSomething2(); }
}
As you can see the clean function can be also called from within the private methods.
Also notice that through the use of static functions the reference to the instance is never leaked, so instances assigned to different threads won't get mixed.
This works quite ok, but then I got another requirement:
Different threads may need to utilize different implementations of Manager class
So I defined an interface:
public interface ManagerHandler {
void method1();
int method2();
}
And modified the Manager class:
public class Manager {
private final static ThreadLocal<ManagerHandler> local = new ThreadLocal<ManagerHandler>();
public static void start(int argument) {
ManagerHandler handler;
// depending on the context initialize handler to whatever class it is necessary
local.set(handler);
}
public static void clean() { local.remove(); }
public static void function1() { local.get().method1(); }
public static int function2() { return local.get().method2(); }
}
An example implementation would look like this:
public class ExampleManagerImplementation implements ManagerHandler {
private int x;
public ExampleManagerImplementation(int argument) { x = argument; }
public void method1() { x++; .... }
public int method2() { if (--x == 0) Manager.clean(); ... }
}
Manager class works here as a facade, forwarding all the calls to the appropriate handler. There is one big issue with this approach: I need to define all the functions both in the Manager class and in the ManagerHandler interface. Unfurtunately Manager class can't implement ManagerHandler interface, because it has static functions rather than methods.
The question is: can you think of a better/easier way to accomplish all the goals I've listed above that would be free of this issue?

There is not much you can do, as you basically need to proxy interface methods through static methods. I could only think of two ways to achieve the same functionality differently:
If you're using a DI framework, you can get rid of the static Manager and use an injected implementation of ManagerHandler which will contain the ThreadLocal.
Generate (as in 'bytecode generation') the static ManagerAccess class using the methods found in the ManagerHandler interface.
Personally, I wouldn't think of having the static ManagerAccess class (which contains the ThreadLocal) around as a serious design issue. At least as long as it keeps to its own set of responsibilities (accessing thread-scoped instances and proxying calls) and doesn't venture anywhere else.

If you're going with this design, is it necessary for Manager to totally hide ManagerHandler interface, or could you expose it so you don't have to delegate every method?
class Manager {
public static ManagerHandler getHandler() { return local.get(); }
}

The trick for creating a singleton per thread class is to use ThreadStatic attribute on your private static _current field which makes it scoped by thread. In this way, the _current field will be stored inside thread memory which is not accessible for the other threads and not shared memory of AppDomain. So, it will be available only in the scope of the thread. On the other hand, the Current property is accessible across all threads in that AppDomain but when it is called it will return the correct instance for that thread. Here is the code that you need:
public sealed class Manager
{
// As you are using the ThreadStatic here you cannot
// call the static constructor or use the Lazy implimentation for
// thread-safty and you have to use the old fashin Lock and anti-pattern.
private static readonly object _criticalArea = new object();
[ThreadStatic]
private static Manager _current;
public static Manager Current
{
get
{
if (_current == null)
{
lock (_criticalArea)
{
if (_current == null)
{
_current = new Manager();
}
}
}
return _current;
}
}
private Manager()
{
}
public string WhatThreadIsThis { get; set; }
}
[TestClass]
public class SingeltonPerThreadTest
{
private readonly EventWaitHandle _threadHandler = new EventWaitHandle(false, EventResetMode.AutoReset);
private string _sharedMemory = "I am the shared memory and yet in main thread :(";
[TestMethod]
public void TestSingeltonPerThread()
{
// Creates a _current for main thread.
Manager.Current.WhatThreadIsThis = "I am the main thread :)";
// Start another thread.
(new Thread(CallTheThreadBaseSingelton)).Start();
// Wait for it to be finished.
_threadHandler.WaitOne();
Assert.AreEqual("I am the main thread :)", Manager.Current.WhatThreadIsThis, "I am not the main thread :( ");
Assert.AreEqual("I am the other thread ;)", _sharedMemory, _sharedMemory);
}
private void CallTheThreadBaseSingelton()
{
// Creates a _current for this thread (this thread is the other one :)) ).
Manager.Current.WhatThreadIsThis = "I am the other thread ;)";
_sharedMemory = Manager.Current.WhatThreadIsThis;
_threadHandler.Set();
}
}
Cheers.

Related

Constructor newInstance generates local instance only

Looks I miss something in my tests (Robolectrics|Powermockito).
I have following class with Singleton:
public class Core{
private static Core instance = new Core();
public static Core getInstance() {
return instance;
}
public static void destroy(){
instance = null;
}
}
In my tests I kill the instance with Core.destroy()
and therefore Core.getInstance() returns null.
So every test I want to re-generate instance again. I do the following:
Constructor<Core> constructor = Core.class.getDeclaredConstructor();
constructor.setAccessible(true);
Core newCore = constructor.newInstance();
So now newCore is initialized but Core.getInstance() still returns null.
How to initialize properly Core -> instance?
There is an important point that I often try to explain to people when talking about singletons:
There's a difference between a singleton and something that you will only create 1 instance of. And, often, when you think you want a singleton, actually you just want something that you will only create 1 instance of.
The difference between these two things is perhaps not apparent at first, but important to realize, especially when you find yourself in a position where you need to purge the internal state of a singleton between tests.
If you have a singleton - a true singleton - there is, by definition, one instance that can exist in the JVM. If this has mutable state, this is problematic, because it means that you have to care about that state. In tests, you have to clear state between runs to remove any effects owing to the ordering of test execution; and you have to run your tests serially.
If you use dependency injection (as in the concept, not any particular framework like Guice, Dagger, Spring etc), it doesn't matter to classes using the instance where that instance came from: you, as a client of the class, get control over its life cycle. So, whereas your production code uses the same instance in all places, your testing code can use separate instances - thus they are decoupled - and often you don't even have to worry about cleaning up state at all, because your next test case can simply create a new instance of the class.
So, instead of code using your Core class like so:
class MyClass {
void foo() {
Core core = Core.getInstance();
// ... do stuff with the Core instance.
}
}
you can write it instead like:
class MyClass {
private final Core core;
MyClass(Core core) { this.core = core; }
void foo() {
// ... do stuff with the Core instance.
}
}
and you have broken the static binding between MyClass and Core. You can instantiate MyClass in tests with separate instances of Core:
MyClass myClass = new MyClass(new Core());
// Assert something...
or, if multiple instances need to interact with the same instance of Core:
Core core = new Core();
MyClass myClass = new MyClass(core);
MyOtherClass myOtherClass = new MyOtherClass(core);
// Assert something...
You should make the constructor private so that code using you singleton class cannot create an instance using it and they should only get an instance using the getInstance() method.
Also the lifetime of a singleton object is typically tied to the JVM, as there should be a single instance of a singleton class per JVM. So if you can destroy and re-create the instance it is not a true Singleton IMO, so I assume you only want to re-create the instance for testing.
To re-create the singleton from your test classes after calling the destroy() method you can get the Field of the class having the instance of your class. Using that Field you can set it to the new instance you created:
public static void main(String[] args) throws Exception {
System.out.println(Core.getInstance()); //gets instance
Core.destroy();
System.out.println(Core.getInstance()); // null
reinitializeInstance(Core.class);
System.out.println(Core.getInstance()); //gets instance
}
public static void reinitializeInstance(Class<Core> clazz) {
try {
Constructor<Core> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
Core newCore = constructor.newInstance();
Field field = Core.class.getDeclaredField("instance"); //gets the instance field
field.setAccessible(true);
field.set(newCore, newCore);
} catch (Exception e) {
e.printStackTrace();
}
}
And your Singleton class:
class Core {
private static Core instance = new Core();
// To prevent reflection from creating a new instance without destroying the first one
private Core() {
if(instance != null){
throw new IllegalStateException("Instance already exists!");
}
}
public static Core getInstance() {
return instance;
}
public static void destroy() {
instance = null;
}
}
public class Core {
private static class SingletonHolder {
private static AtomicReference<Core> instance = new AtomicReference(new Core());
}
public static Core getInstance() {
return SingletonHolder.instance.get();
}
public static void destroy() {
SingletonHolder.instance.set(null);
}
public static void reset() {
SingletonHolder.instance.compareAndSet(null, new Core());
}
}
Using an extra "superfluous" inner class is done for concurrent initialisation, ensuring that the static field is initialized once.
Changing the instance (destroy, my reset) needs some kind of synchronisation for objects.
Instead of the more costly synchronize one can use an AtomicReference.
compareAndSet does not set the instance with a new value, if there is already an old value.
It is also worth having
Optional<Core> getInstance() { ... }
So the usage is safe-guarded.
Core.getInstance().ifPresent(core -> { ... core ... });
First of all you're making Core constructor accessible, but it's public by default already.
Second, when your calling the constructor, it just creates a new instance of Core, which does nothing to instance, because constructor, created by default is empty and because constructor is not the place to initialize Singleton.
If you want to refresh singleton instance you should have a dedicated method for that.
How about this pattern instead?
public class Core{
private static Core instance;
public static Core getInstance() {
if(instance == null) instance = new Core();
return instance;
}
public static void destroy(){
instance = null;
}
}
And if you only want to destory in tests, you can remove "public" from your destroy() method

Code refactoring, how to disintegrate two two static functions without making parent functions non static

Context :
We are refectoring the code in order to move to micro services. We've
multiple products(A, B, C and some common code for A,B,C in monolithic
service). now we creating new sandbox for common code.
Problem :
User.java
Class User {
public **static** void init(){
List<Items> users=Items.getItemsList();
}
}
Items.java
Class Items {
public **static** Items getItemsList(){
//many static functions and dependancy
return items;
}
}
So here, both the functions are static and i want to move only User.java
to new sandbox not Items.java. how can i disintegrate this dependancy.
and i can not make User.init() non-static
Assuming sandbox means an independent project that produces a jar, then 'Items` must also exist in the sandbox, otherwise it won't compile.
But you could extract an interface from Items to something such as IItems (forgive the terrible name).
public interface IItems {
// methods...
}
which is included in the sandbox.
And create an interface for a factory such as:
public interface IItemsFactory {
List<IItem> create();
}
which is also included in the sandbox.
The ugly part is keeping User.init() as static. Using a hacky IoC pattern, set an implementation of an IItemsFactory into User. The factory will also have to be static. So User becomes something like:
public class User {
private static volatile IItemsFactory factory;
public static setFactory(IItemsFactory factory) {
User.factory = factory;
}
public static void init() {
List<IItems> users = factory.getItemsList();
}
}
The A, B, and C projects are responsible for providing an implementation of IItemFactory and setting it before calling User.init().
This is half baked and those static methods need to go away during the next refactoring iteration. Still use the IoC pattern, but inject the factory as part of the User constructor.
public class User {
private IItemsFactory factory;
public User(IItemsFactory factory) {
this.factory = factory;
}
public void init() {
List<IItems> users = factory.getItemsList();
}
}

Pass an object of another class to a singleton class

I am using this singleton class in Java and in one method, I need an object of a class which gets instantiated in Main. I am not knowing how to pass that object to this method because this code is written in the constructor of the singleton class as I need it to be executed as soon as the program starts.
Should I take out the code from the constructor and make it a standalone method which I call from Main (though I wouldn't prefer this) or is there another way?
Any ideas?
Code:
Main:
public static void main(String[] args) {
X x; // This is the object I need to pass to the singleton class
}
Singleton class:
public SomeSingletonClass {
private Queue<Y> someQueue; // Y is another class I have in my project
private SomeSingletonClass(){
someQueue.add(new Y(<some data>, <some data>, <here I need an object of X as the constructor needs it>);
}
}
I haven't added the entire code. Just a fragment where I am stuck.
You have two main options.
The first will produce howls of derision - and rightly so because it is a dark tunnel of hell.
public class X {
}
public class Y {
public Y(String s, X x) {
}
}
public class Main {
public static X x = new X();
}
public class SomeSingletonClass {
private Queue<Y> someQueue = new LinkedList<>();;
private SomeSingletonClass() {
someQueue.add(new Y("Hello", Main.x));
}
}
Here we make the X created by Main a public static so it is now, essentially, global state in parallel with your singleton.
Most readers will understand how nasty this is but it is the simplest solution and therefore often the one taken.
The second option is lazy construction.
public class BetterSingletonClass {
private BetterSingletonClass me = null;
private Queue<Y> someQueue = new LinkedList<>();
private BetterSingletonClass(X x) {
someQueue.add(new Y("Hello", x));
}
public BetterSingletonClass getInstance (X x) {
if ( me == null ) {
me = new BetterSingletonClass(x);
}
return me;
}
}
Note that I have made no effort to make this a real singleton, n'or is this thread-safe. You can search for thread safe singleton elsewhere for plenty of examples.

Ensure static variables are initialized before using any static methods?

I have a monitor class with a static (and optionally final) variable called ClockValues. This variable is used by every other static method. However, the ClockValues object comes from an external source. Is there way I can ensure external objects and threads to initialize ClockValues before using any static methods in this class?
Kind of like a constructor but for static variables.
public class SharedData {
private static final MutexSem mutex = new MutexSem();
private static ClockValues clock;
//my static "Constructor"
//but I can't force other objects to call this method before all other methods in this class
//I understand I could use a flag to signal initilization, but I was looking for a cleaner way
public static void initialize(ClockValues c){
mutex.take();
clock= c;
mutex.give();
}
public static void doSomething(){
mutex.take();
//do something with `clock`
mutex.give();
}
//... more methods using `clock` variable
}
I don't think you can do what you want with static methods. You could probably do something with a singleton pattern:
public class SharedData {
private static final MutexSem mutex = new MutexSem();
private static SharedData instance;
private ClockValues clock;
public static SharedData getInstance(ClockValues c) {
mutex.take();
if (instance == null) {
instance = new SharedData(c);
}
mutex.give();
return instance;
}
private SharedData(ClockValues c) {
clock = c;
}
public void doSomething() { // NOTE: no longer static
mutex.take();
//do something with `clock`
mutex.give();
}
//...
}
Unfortunately, that would require every call to getInstance to have a ClockValues value to pass as an argument. Depending on your architecture, though, this might be a feasible alternative.
the standard pattern to initialize singletons is described in Effective Java, Second Edition, Item 71:
public class AService {
private static int init = 0;
private static class Holder {
private static final AService theService = new AService(init);
}
private AService(int init) {
System.out.println("AService instance initialized with " + init);
}
public static AService instance(int init) {
AService.init = init;
return Holder.theService;
}
}
Thus instantiation of the service singleton is delayed until first call to instance (which may took additional arguments etc) and you may perform a more complex instantiation. Depending on your project initialization logic you may split .instance(init) into .getFirstInstance(init) and .instance(), but this is solely up to you.

Singleton & Multithreading in Java

What is the preferred way to work with Singleton class in multithreaded environment?
Suppose if I have 3 threads, and all of them try to access getInstance() method of singleton class at the same time -
What would happen if no synchronization is maintained?
Is it good practice to use synchronized getInstance() method or use synchronized block inside getInstance().
Please advise if there is any other way out.
If you're talking about threadsafe, lazy initialization of the singleton, here is a cool code pattern to use that accomplishes 100% threadsafe lazy initialization without any synchronization code:
public class MySingleton {
private static class MyWrapper {
static MySingleton INSTANCE = new MySingleton();
}
private MySingleton () {}
public static MySingleton getInstance() {
return MyWrapper.INSTANCE;
}
}
This will instantiate the singleton only when getInstance() is called, and it's 100% threadsafe! It's a classic.
It works because the class loader has its own synchronization for handling static initialization of classes: You are guaranteed that all static initialization has completed before the class is used, and in this code the class is only used within the getInstance() method, so that's when the class loaded loads the inner class.
As an aside, I look forward to the day when a #Singleton annotation exists that handles such issues.
Edited:
A particular disbeliever has claimed that the wrapper class "does nothing". Here is proof that it does matter, albeit under special circumstances.
The basic difference is that with the wrapper class version, the singleton instance is created when the wrapper class is loaded, which when the first call the getInstance() is made, but with the non-wrapped version - ie a simple static initialization - the instance is created when the main class is loaded.
If you have only simple invocation of the getInstance() method, then there is almost no difference - the difference would be that all other sttic initialization would have completed before the instance is created when using the wrapped version, but this is easily dealt with by simply having the static instance variable listed last in the source.
However, if you are loading the class by name, the story is quite different. Invoking Class.forName(className) on a class cuasing static initialization to occur, so if the singleton class to be used is a property of your server, with the simple version the static instance will be created when Class.forName() is called, not when getInstance() is called. I admit this is a little contrived, as you need to use reflection to get the instance, but nevertheless here's some complete working code that demonstrates my contention (each of the following classes is a top-level class):
public abstract class BaseSingleton {
private long createdAt = System.currentTimeMillis();
public String toString() {
return getClass().getSimpleName() + " was created " + (System.currentTimeMillis() - createdAt) + " ms ago";
}
}
public class EagerSingleton extends BaseSingleton {
private static final EagerSingleton INSTANCE = new EagerSingleton();
public static EagerSingleton getInstance() {
return INSTANCE;
}
}
public class LazySingleton extends BaseSingleton {
private static class Loader {
static final LazySingleton INSTANCE = new LazySingleton();
}
public static LazySingleton getInstance() {
return Loader.INSTANCE;
}
}
And the main:
public static void main(String[] args) throws Exception {
// Load the class - assume the name comes from a system property etc
Class<? extends BaseSingleton> lazyClazz = (Class<? extends BaseSingleton>) Class.forName("com.mypackage.LazySingleton");
Class<? extends BaseSingleton> eagerClazz = (Class<? extends BaseSingleton>) Class.forName("com.mypackage.EagerSingleton");
Thread.sleep(1000); // Introduce some delay between loading class and calling getInstance()
// Invoke the getInstace method on the class
BaseSingleton lazySingleton = (BaseSingleton) lazyClazz.getMethod("getInstance").invoke(lazyClazz);
BaseSingleton eagerSingleton = (BaseSingleton) eagerClazz.getMethod("getInstance").invoke(eagerClazz);
System.out.println(lazySingleton);
System.out.println(eagerSingleton);
}
Output:
LazySingleton was created 0 ms ago
EagerSingleton was created 1001 ms ago
As you can see, the non-wrapped, simple implementation is created when Class.forName() is called, which may be before the static initialization is ready to be executed.
The task is non-trivial in theory, given that you want to make it truly thread safe.
A very nice paper on the matter is found # IBM
Just getting the singleton does not need any sync, since it's just a read. So, just synchronize the setting of the Sync would do. Unless two treads try to create the singleton at start up at the same time, then you need to make sure check if the instance is set twice (one outside and one inside the sync) to avoid resetting the instance in a worst case scenario.
Then you might need to take into account how JIT (Just-in-time) compilers handle out-of-order writes. This code will be somewhat near the solution, although won't be 100% thread safe anyway:
public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
Singleton inst = instance;
if (inst == null) {
synchronized(Singleton.class) {
instance = new Singleton();
}
}
}
}
return instance;
}
So, you should perhaps resort to something less lazy:
class Singleton {
private static Singleton instance = new Singleton();
private Singleton() { }
public static Singleton getInstance() {
return instance;
}
}
Or, a bit more bloated, but a more flexible way is to avoid using static singletons and use an injection framework such as Spring to manage instantiation of "singleton-ish" objects (and you can configure lazy initialization).
You need synchronization inside getInstance only if you initialize your singleton lazily. If you could create an instance before the threads are started, you can drop synchronization in the getter, because the reference becomes immutable. Of course if the singleton object itself is mutable, you would need to synchronize its methods which access information that can be changed concurrently.
This question really depends on how and when your instance is created. If your getInstance method lazily initializes:
if(instance == null){
instance = new Instance();
}
return instance
Then you must synchronize or you could end up with multiple instances. This problem is usually treated in talks on Double Checked Locking.
Otherwise if you create a static instance up front
private static Instance INSTANCE = new Instance();
then no synchronization of the getInstance() method is necessary.
The best way as described in effective java is:
public class Singelton {
private static final Singelton singleObject = new Singelton();
public Singelton getInstance(){
return singleObject;
}
}
No need of synchronization.
Nobody uses Enums as suggested in Effective Java?
If you are sure that your java runtime is using the new JMM (Java memory model, probably newer than 5.0), double check lock is just fine, but add a volatile in front of instance. Otherwise, you'd better use static internal class as Bohemian said, or Enum in 'Effective Java' as Florian Salihovic said.
For simplicity, I think using enum class is a better way. We don't need to do any synchronization. Java by construct, always ensure that there is only one constant created, no matter how many threads are trying to access it.
FYI, In some case you need to swap out singleton with other implementation. Then we need to modify class, which is violation of Open Close principal.Problem with singleton is, you can't extend the class because of having private constructor. So, it's a better practice that client is talking via interface.
Implementation of Singleton with enum class and Interface:
Client.java
public class Client{
public static void main(String args[]){
SingletonIface instance = EnumSingleton.INSTANCE;
instance.operationOnInstance("1");
}
}
SingletonIface.java
public interface SingletonIface {
public void operationOnInstance(String newState);
}
EnumSingleton.java
public enum EnumSingleton implements SingletonIface{
INSTANCE;
#Override
public void operationOnInstance(String newState) {
System.out.println("I am Enum based Singleton");
}
}
The Answer is already accepted here, But i would like to share the test to answer your 1st question.
What would happen if no synchronization is maintained?
Here is the SingletonTest class which will be completely disaster when you run in multi Threaded Environment.
/**
* #author MILAN
*/
public class SingletonTest
{
private static final int PROCESSOR_COUNT = Runtime.getRuntime().availableProcessors();
private static final Thread[] THREADS = new Thread[PROCESSOR_COUNT];
private static int instancesCount = 0;
private static SingletonTest instance = null;
/**
* private constructor to prevent Creation of Object from Outside of the
* This class.
*/
private SingletonTest()
{
}
/**
* return the instance only if it does not exist
*/
public static SingletonTest getInstance()
{
if (instance == null)
{
instancesCount++;
instance = new SingletonTest();
}
return instance;
}
/**
* reset instancesCount and instance.
*/
private static void reset()
{
instancesCount = 0;
instance = null;
}
/**
* validate system to run the test
*/
private static void validate()
{
if (SingletonTest.PROCESSOR_COUNT < 2)
{
System.out.print("PROCESSOR_COUNT Must be >= 2 to Run the test.");
System.exit(0);
}
}
public static void main(String... args)
{
validate();
System.out.printf("Summary :: PROCESSOR_COUNT %s, Running Test with %s of Threads. %n", PROCESSOR_COUNT, PROCESSOR_COUNT);
long currentMili = System.currentTimeMillis();
int testCount = 0;
do
{
reset();
for (int i = 0; i < PROCESSOR_COUNT; i++)
THREADS[i] = new Thread(SingletonTest::getInstance);
for (int i = 0; i < PROCESSOR_COUNT; i++)
THREADS[i].start();
for (int i = 0; i < PROCESSOR_COUNT; i++)
try
{
THREADS[i].join();
}
catch (InterruptedException e)
{
e.printStackTrace();
Thread.currentThread().interrupt();
}
testCount++;
}
while (instancesCount <= 1 && testCount < Integer.MAX_VALUE);
System.out.printf("Singleton Pattern is broken after %d try. %nNumber of instances count is %d. %nTest duration %dms", testCount, instancesCount, System.currentTimeMillis() - currentMili);
}
}
Output of the program is clearly shows that you need handle this using getInstance as synchronized or add synchronized lock enclosing new SingletonTest.
Summary :: PROCESSOR_COUNT 32, Running Test with 32 of Threads.
Singleton Pattern is broken after 133 try.
Number of instance count is 30.
Test duration 500ms

Categories

Resources