Hashmap updates not reflected between threads - java

I have a singleton class that contains a hahsmap, the hashmap is initialised as a class variable. This map is updated correctly because when i add and print the size it changed, but, when i call it from a different thread the map is always empty. Is there a particular reason why this might happen?
I am using a ConccurentHashMap if this makes any difference.
Thanks
Singleton decleration:
public class ClientRegistryDetailsSingleton {
private static ClientRegistryDetailsSingleton instance = null;
private ConcurrentHashMap<String, Integer> tickerToNumberRegistered = new ConcurrentHashMap<String,Integer>();
protected ClientRegistryDetailsSingleton() {
// Exists only to defeat instantiation.
}
public static ClientRegistryDetailsSingleton getInstance() {
if(instance == null) {
instance = new ClientRegistryDetailsSingleton();
}
return instance;
}
public void setTickerToNumberRegistered(ConcurrentHashMap<String, Integer> tickerToNumberRegistered) {
this.tickerToNumberRegistered = tickerToNumberRegistered;
}
public ConcurrentHashMap<String, Integer> getTickerToNumberRegistered() {
return tickerToNumberRegistered;
}
public void addToClienets(String ticker){}
public void removeFromClients(String ticker){}
}
Calling it from another thread:
String[] splitForTicker = message.split(",");
ConcurrentHashMap<String, Integer> map = ClientRegistryDetailsSingleton.getInstance().getTickerToNumberRegistered();
System.out.println("The number of items in the map from senders persepctive" + map.size());
Output:
The number of items in the map from senders persepctive 0
2012-11-12 14:29:12,495 [Process messages received] INFO com.feed.feedReceive.ProcessFeedStreamLine - Successfully received a message from the feed
The number of items in the map from senders persepctive 0
1 :the size of the map now someone has added
2012-11-12 14:29:15,495 [Process messages received] INFO com.feed.feedReceive.ProcessFeedStreamLine - Successfully received a
message from the feed
The number of items in the map from senders persepctive 0
New code for Singleton
public class ClientRegistryDetailsSingleton {
private static ClientRegistryDetailsSingleton instance = new ClientRegistryDetailsSingleton();
private volatile ConcurrentHashMap<String, Integer> tickerToNumberRegistered = new ConcurrentHashMap<String,Integer>();
protected ClientRegistryDetailsSingleton() {
// Exists only to defeat instantiation.
}
public static synchronized ClientRegistryDetailsSingleton getInstance() {
return instance;
}
public synchronized ConcurrentHashMap<String, Integer> getTickerToNumberRegistered() {
return tickerToNumberRegistered;
}
public void addToClienets(String ticker){}
public void removeFromClients(String ticker){}
}

There is a race condition in the posted code that can result in more that one instance of the singleton being constructed if two threads call getInstance() and the singleton has not yet been constructed:
public static ClientRegistryDetailsSingleton getInstance() {
if(instance == null) { // Line 1
instance = new ClientRegistryDetailsSingleton(); // Line 2
}
}
A possible execution of two threads, T1 and T2:
T1 peforms check at line 1 and enters if branch.
T1 is suspended, with instance still being null.
T2 peforms check at line 1 and enters if branch.
T2 constructs class and assigns to instance.
T2 returns instance to caller.
T2 is suspended.
T1 is started again and constructs another instance and assigns to instance.
The construction of the single instance must be threadsafe. Possible solutions would be:
Make the getInstance() method synchronized.
Don't use lazy initialization (if possible):
private static final ClientRegistryDetailsSingleton instance =
new ClientRegistryDetailsSingleton();

Define your hash map as
private volatile ConcurrentHashMap<String, Integer>
The volatile keyword warns the JVM that the state of the variable may be changed by another thread at any time, so it must not be cached locally.
Defining the instance also as volatile might also be necessary.

Implementation of DCL antipattern: http://en.wikipedia.org/wiki/Double_checked_locking
public class ClientRegistryDetailsSingleton {
private static volatile ClientRegistryDetailsSingleton instance = null;
private final ConcurrentHashMap<String, Integer> tickerToNumberRegistered = new ConcurrentHashMap<String,Integer>();
private ClientRegistryDetailsSingleton() {
// Exists only to defeat instantiation.
// please not that constructor should be private
}
public static ClientRegistryDetailsSingleton getInstance() {
if (instance == null) {
synchronized(ClientRegistryDetailsSingleton.class){
if(instance == null)
instance = new ClientRegistryDetailsSingleton();
}
}
return instance;
}
//You should not break encapsulation and allow a link to HashMap escape
private void setTickerToNumberRegistered(ConcurrentHashMap<String, Integer> tickerToNumberRegistered) {
this.tickerToNumberRegistered = tickerToNumberRegistered;
}
//You should not break encapsulation and allow a link to HashMap escape
private ConcurrentHashMap<String, Integer> getTickerToNumberRegistered() {
}
//I omitted the access to the hash map it's likely that some additional params required
public void addToClienets(String ticker){}
//I omitted the access to the hash map it's likely some additional params are required
public void removeFromClients(String ticker){}
}
I've shown this only as a synchronization example, in real life you should likely implement your singletons as Enums : What is the best approach for using an Enum as a singleton in Java?

Related

Have static method return the same instance for the same string argument

I have a TrafficMonitor class, inside the class, I have a factory static method to return an instance of this class:
public class TrafficMonitor {
private String busNumber;
//private constructor
private TrafficMonitor(String busNumber) {
this.busNumber = busNumber;
}
// static factory method to return a instance of this class
public static TrafficMonitor forBus(String busNumber) {
// how to make sure one instance per busNumber???
return new TrafficMonitor(busNumber);
}
}
I don't want the TrafficMonitor to be a singleton overall. But inside the static factory method forBus(String busNumber), I would like to make sure the same instance of TrafficMonitor is return for the same busNumber. That's "singleton" per busNumber. How to achieve it?
For example following code should use the same instance of TrafficMonitor:
// monitor1 and monitor2 are referring to the same instance
TrafficMonitor monitor1 = TrafficMonitor.forBus("123");
TrafficMonitor monitor2 = TrafficMonitor.forBus("123");
Following code should use different instances of TrafficMonitor:
// monitor1 and monitor2 are two different instances
TrafficMonitor monitor1 = TrafficMonitor.forBus("123");
TrafficMonitor monitor2 = TrafficMonitor.forBus("456");
And I want to have the static factory method be thread safe as well. That's if two threads call it for the same bus number, two threads should use the same instance as well.
Add instances to a static map. Use computeIfAbsent to return the existing instance if the key already exists or create a new one if it doesn't.
A ConcurrentMap ensures thread safety.
private static ConcurrentMap<String, TrafficMonitor> instances = new ConcurrentHashMap<>();
public static TrafficMonitor forBus(String busNumber) {
return instances.computeIfAbsent(busNumber, TrafficMonitor::new);
}

How to avoid the performance overhead of using volatile in singleton pattern?

Say Code for Singleton pattern:
class Singleton
{
private volatile static Singleton obj;
private Singleton() {}
public static Singleton getInstance()
{
if (obj == null)
{
synchronized (Singleton.class)
{
if (obj==null)
obj = new Singleton();
}
}
return obj;
}
}
obj in the above code is marked as Volatile, which means that whenever obj is used in the code, its always fetched from the main memory instead of using the cached value. So whenever if(obj==null) needs to be performed it fetches obj from main memory, though its value is set in the previous run. This is a performance overhead of using volatile keyword. How do we avoid it?
You have a serious miss-understanding what volatile does, but to be fair the internet and stackoverflow including is just polluted with wrong or incomplete answers about this. I also admit that I think I have a good grab about it, but sometimes have to re-read some things again.
What you have there shown - is called the "double check locking" idiom and it's a perfectly valid use-case to create a singleton. The question is if you really need it in your case (the other answer has shown a far more simple way, or you can read the "enum singleton pattern" too if you want). It's a bit funny how many people know that volatile is needed for this idiom, but can't really tell why it is needed.
DCL is doing two things mainly - ensures atomicity (multiple threads can't not enter the synchronized block at the same time) and ensures that once created, all threads will see that created instance, called visibility. At the same time, it ensures that the synchronized block will be entered a single time, all threads after that will not need to do that.
You could have easily done it via:
private Singleton instance;
public Singleton get() {
synchronized (this) {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
But now every single Thread that needs that instance has to compete for the lock and has to enter that synchronized block.
Some people think that: "hey, I can work around that!" and write (thus enter the synchronized block only once):
private Singleton instance; // no volatile
public Singleton get() {
if (instance == null) {
synchronized (this) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
As simple as that is - that is broken. And this isn't easy to explain.
it is broken because there are two independent reads of instance; JMM allow for these to be re-ordered; thus it is entirely valid that if (instance == null) does not see a null; while return instance; sees and returns a null. Yes, this is counter-intuitive, but entirely valid and provable (I can write a jcstress test to prove this in 15 minutes).
the second point is a bit more tricky. Suppose your singleton has a field that you need to set.
Look at this example:
static class Singleton {
private Object some;
public Object getSome() {
return some;
}
public void setSome(Object some) {
this.some = some;
}
}
And you write code like this to provide that singleton:
private Singleton instance;
public Singleton get() {
if (instance == null) {
synchronized (this) {
if (instance == null) {
instance = new Singleton();
instance.setSome(new Object());
}
}
}
return instance;
}
Since the write to the volatile (instance = new Singleton();) happens before setting the field that you need instance.setSome(new Object());; some Thread that reads this instance might see that instance is not null, but when doing instance.getSome() will see a null. The correct way to do this would be (plus making the instance volatile):
public Singleton get() {
if (instance == null) {
synchronized (this) {
if (instance == null) {
Singleton copy = new Singleton();
copy.setSome(new Object());
instance = copy;
}
}
}
return instance;
}
Thus volatile here is needed for safe publication; so that the published reference is "safely" seen by all threads - all it's fields are initialized. There are some other ways to safely publish a reference, like final set in the constructor, etc.
Fact of life: reads are cheaper than writes; you should not care what volatile reads do under the hood as long as your code is correct; so don't worry about "reads from main memory" (or even better don't use this phrase without even partially understanding it).
If you want to avoid using volatile, Then you can initialize when class loading and use private constructor to avoid creating new instance.
public class Singleton{
//Initialized when class loading
private static final Singleton INSTANCE = new Singleton();
//To avoid creating new instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
You can use Lazy initialization with Holder static class
class Singleton
{
private Singleton() {}
private static class LazyLoader{
static final Singleton obj = new Singleton();
}
public static Singleton getInstance()
{
return LazyLoader.obj;
}
}
The important thing to note here is that the constructor should be fail-safe otherwise class loader will throw NoClassDefFoundError
You should use Enums for Singleton implementation.
Joshua Bloch suggests the use of Enum to implement Singleton design pattern because Java will ensures that any enum value is instantiated only once in a Java
program. The drawback is that the enum type is somewhat inflexible; for
example, it does not allow lazy initialization.
public enum EnumSingleton {
INSTANCE;
int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public class EnumDemo {
public static void main(String[] args) {
EnumSingleton singleton = EnumSingleton.INSTANCE;
System.out.println(singleton.getValue());
singleton.setValue(2);
System.out.println(singleton.getValue());
}
}
This post by has nicely listed other benefits of using Enums:
java singleton instantiation

How to extend a singleton class to handle a specific number of objects

In Java, I have created a singleton class as follows:
public class Singleton
{
private Singleton() { print("Singleton Constructor"); }
private static Singleton pointer = new Singleton();//static here so only one object
public static Singleton makeSingleton()
{
return pointer;
}
public static void main (String args[])
{
Singleton nuReference = Singleton.makeSingleton();
if(nuReference == pointer)
{
print("Both are references for same object.");
}
}
}
Here, only the reference to an already-created object of Singleton class is being returned. How can I create a class so that only, say, four objects of that class are allowed to be created? Can I use this Singleton class for that or do I have to make it from scratch?
Oh, and print() is my custom method here. Works the same as System.out.println(), just with fewer keystrokes :)
That should work:
public class Singleton
{
private Singleton()
{
print("Constructor");
}
private static Singleton instances[] = new Singleton[4];
private static Boolean initiated = false;
public static Singleton getInstance(int index)
{
tryInitiate();
if(instances[index] == null)
{
instances[index] = new Singleton();
}
return instances[index];
}
private static Boolean tryInitiate()
{
if(initiated) return false;
for (int i = 0; i < instances.length; i++)
{
instances[i] == null;
}
initiated = true;
return true;
}
}
Instead of initiating the objects with "null" you could also instantiate the objects during the initiation. But this way only the needed objects are instantiated.
Add a static int count = numyouwant; to your code, every time the static creation method is called, reduce the count by 1. and more importantly, check whether count is 0 before call the private constructor in the creation method~
Singletons, by definition, only have a single instance of itself. What you're suggesting sounds like you would make better use of a Factory-type paradigm, along with a counter/limiter (built into the class).
Make a Factory class that contains a counter (or a list to store created objects, if you prefer) and a createObject method. In the method, do your logic for determining whether there are too many objects, and therefore you may limit creation of the objects.
Here's an example of a Factory with a max limit on created objects. The object in question is an inner class for simplicity.
public class Factory {
private final int maxObj = 4;
public class MyObject {
MyObject() { print("Constructor"); }
}
private List<MyObject> objects = new List<Object>();
// Returns new MyObject if total MyObject
// count is under maxObj, null otherwise
public MyObject makeObject() {
if (objects.length() >= maxObj)
return null;
MyObject obj = new MyObject();
objects.add(obj);
return obj;
}
}
create a variable x
increase its value every time when makeSingleton is called
if x<4 then return pointer
else return null
Create a field of List<Singleton> mySingletons; and a field int singletonCounter=0;
in makeSingleton() method add 1 to counter if it is equal to 4 return null or return a singleton of 4.If counter is less than 4 then create a singleton.
my question is that how can i create a class so that say only 4 objects of that class are allowed to be created. any help ?
can i use this Singleton class for that or do i have to make it from scratch ?
I believe you want to keep a pool of objects of a class . You can't do it through a Singleton class , which by definition should return the only instance it has.
Suggested reads:
Object Pool in Java
.
Build your own ObjectPool
You could add a Queue of 4 instances of the same object, and manage the queue/dequeue operations.
Beware: Sounds you should apply thread-safety for those operations.
I created one with Thread Safty
import java.util.ArrayList;
import java.util.List;
public class SingletonLimit{
private List<SingletonLimit> inst_Obj= new ArrayList<>();
private static final int maxLimit=4;
private SingletonLimit(){
}
public SingletonLimit getInstance(){
if(inst_Obj.size()>=maxLimit)
return null;
SingletonLimit singleLimit=null;
synchronized(SingletonLimit.class){
singleLimit= new SingletonLimit();
inst_Obj.add(singleLimit);
}
return singleLimit;
}
}

Incorrect lazy initialization

Findbug told me that I use incorrect lazy initialization.
public static Object getInstance() {
if (instance != null) {
return instance;
}
instance = new Object();
return instance;
}
I don't see anything wrong here. Is it wrong behaviour of findbug, or I missed something?
Findbug is referencing a potential threading issue. In a multi thread environment, there would be potential for your singleton to be created more than once with your current code.
There is a lot of reading here, but it will help explain.
The race condition here is on the if check. On the first call, a thread will get into the if check, and will create the instance and assign it to 'instance'. But there is potential for another thread to become active between the if check and the instance creation/assignment. This thread could also pass the if check because the assignment hasn't happened yet. Therefore, two (or more, if more threads got in) instances would be created, and your threads would have references to different objects.
Your code is slightly more complex than needed which might be why it's confused.
Edit: It's definitely the threading issue as the others posted but thought I'd post the double lock check implementation here for reference below:
private static final Object lock = new Object();
private static volatile Object instance; // must be declared volatile
public static Object getInstance() {
if (instance == null) { // avoid sync penalty if we can
synchronized (lock) { // declare a private static Object to use for mutex
if (instance == null) { // have to do this inside the sync
instance = new Object();
}
}
}
return instance;
}
NOTE: JohnKlehm's double lock checking solution is better. Leaving this answer here for historical reasons.
It should actually be
public synchronized static Object getInstance() {
if (instance == null) {
instance = new Object();
}
return instance;
}
You need to put a lock around instantiation to make this correct
LI: Incorrect lazy initialization of static field
(LI_LAZY_INIT_STATIC)
This method contains an unsynchronized lazy initialization of a
non-volatile static field. Because the compiler or processor may
reorder instructions, threads are not guaranteed to see a completely
initialized object, if the method can be called by multiple threads.
You can make the field volatile to correct the problem. For more
information, see the Java Memory Model web site.
You missed multi threading issue,
private static Object instance;
public static synchronized Object getInstance() {
return (instance != null ? instance : (instance = new Object()));
}
Thanks to John Klehm for posted sample
also may try to assign object instance in sychronised block directly
synchronized (MyCurrentClass.myLock=new Object())
i.e.
private static volatile Object myLock = new Object();
public static Object getInstance() {
if (instance == null) { // avoid sync penalty if we can
synchronized (MyCurrentClass.myLock**=new Object()**) { // declare a private static Object to use for mutex
if (instance == null) { // have to do this inside the sync
instance = new Object();
}
}
}
return instance;
}
your static object is not synchronized. Moreover your method is not a lazy initialization. Normally what you do is you keep a Map of object,and you initialize the desired one on demand. So you do not initialize all of them at the beginning rather than calling them when it is needed(called).
Since 1.5: the instance should be volatile and yould integrate a tmp variable to avoid using an instance that is created but its initialization is not finished yet.
private static volatile Object myLock = new Object();
private static volatile Object instance;
public static Object getInstance() {
if (instance == null) {
Object tmpObj;
synchronized (myLock) {
tmpObj = instance;
if (tmpObj == null) {
tmpObj = new Object();
}
}
instance = tmpObj;
}
return instance;
}

How to defend Singleton class methods to be thread safe in Java?

I have thread safe double checked Singleton class that holds a LinkedList with get/set/size methods in the Singleton class. Then I have simple pool class that is using this Singleton class to manage pool of objects.
My question is how can I defend the methods of get/set both in the singleton and the pool class without using sync methods. Here's my code
public class SingletonDoubleCheckedLockingPattern {
private static SingletonDoubleCheckedLockingPattern s = new SingletonDoubleCheckedLockingPattern();
private LinkedList<Object> linkedList;
public int GetListObjectCount() {
return linkedList.size();
}
public Object GetObjectFromList() {
return linkedList.poll();
}
public void SetObjectFromList(Object ee) {
linkedList.add(ee);
}
private SingletonDoubleCheckedLockingPattern() {
linkedList = new LinkedList<Object>();
}
/**
* SingletonHolder is loaded on the first execution of
* Singleton.getInstance() or the first access to SingletonHolder.INSTANCE,
* not before.
*/
private static class SingletonHolder {
public static final SingletonDoubleCheckedLockingPattern INSTANCE = new SingletonDoubleCheckedLockingPattern();
}
public static SingletonDoubleCheckedLockingPattern getInstance() {
return SingletonHolder.INSTANCE;
}
// avoid cloning
public final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
public class SingletonObjectPool {
private int maxlistValue = 10;
public Object GetObject()
{
int listCount = SingletonDoubleCheckedLockingPattern.getInstance().GetListObjectCount();
if(listCount > 0)
{
return SingletonDoubleCheckedLockingPattern.getInstance().GetObjectFromList();
}
return null;
}
public void SetObject()
{
int listCount = SingletonDoubleCheckedLockingPattern.getInstance().GetListObjectCount();
if(listCount < maxlistValue)
{
SingletonDoubleCheckedLockingPattern.getInstance().SetObjectFromList(new Object());
}
}
}
You could use a BlockingQueue which is thread safe. You shouldn't need to check whether a collection is empty before attempting to remove an element, the collection has a method to do this.
To simplify your code and make it thread safe you can do.
public class SingletonObjectPool {
private static final int maxlistValue = 10;
private static final BlockingQueue queue
= new ArrayBlockingQueue(maxListValue);
public static Object getObject() {
return queue.poll();
}
public static void addObjectAsRequired() {
queue.offer(new Object());
}
}
The only way I can think that you can possibly call methods such as GetListObjectCount without using synchronized, is if the list itself is thread-safe and will behave sensibly when this method is called in the face of concurrent modifications.
In that case, there won't be any other problems, as the reference to the list itself never changes. You may want to declare it as final to make this abundantly clear, and to have the compiler warn anyone who tries to reassign the list. (If this were a requirement, the reference would need to be volatile at the very least, but it opens up lots of other questions in the correctness of multiple operations of your class).
The bottom line is that "thread safety" is not a simple, binary concept. You can't just say a particular class and/or method is thread-safe; rather, it's about what combinations of methods you can call with useful and correct semantics.

Categories

Resources