In my project I am using JSON object to sent responce to client.
My JSONObject:
JSONObject jsonObj = new JSONObject();
Every time I am creating an json Object using new key word.
I don't want to create using new key word.
for this Can I implement Singleton pattern for this??
My Singletone Class code:
public class SingletonInstance {
private static SingletonInstance instance = new SingletonInstance ();
private SingletonUmtInstance() {
}
// Get the only object available
public static JSONObject getInstance() {
if (instance == null) {
instance = new JSONObject();
return instance;
} else {
return instance;
}
}
}
to Create an instance I'll use:
JSONObject DBCon = SingletonInstance.getInstance();
Is this the correct way??
Singleton design pattern restricts the instantiation and makes sure that only one instance of the class exists in the JVM.
In other terms, when you implement Singleton, the purpose is to make sure that you use the very same instance each time you invoke the getInstance() method.
Regarding your code, the condition if (instance == null) is useless and your getInstance() method is equivalent to :
public static JSONObject getInstance() {
return instance;
}
Before changing the approach from creating new object to singleton or static way, make sure the application is not used in multithreaded environment.
You would pass the json string to JSONObject constructor means it is holding the state. Changing it to singleton or static leads to inconsistent data in multithreaded environment.
Use enum for singleton implementation.
Sample code snippet:
public enum SingletonEnum {
INSTANCE;
public static JSONObject getJsonObject() {
return new JSONObject();
}
}
Get the instance using
SingletonEnum singleton = SingletonEnum.INSTANCE;
Use the hashcode method in object class to make sure it remains same irrespective of 'n' number of times it was called.
You could do it this way:
public class SingletonInstance {
private SingletonInstance() { }
private static class Holder {
private static final SingletonInstance INSTANCE = new SingletonInstance();
}
public static SingletonInstance getInstance() {
return Holder.INSTANCE;
}
}
This implementation is thread-safe as well.
Related
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
I have a factory class, which I have made singleton using enum. I want to make sure that the object being created is also singleton (Please note that I do not own the class being created, but I want to ensure that it's object is singleton).
I am trying something like this
public enum MyFactoryImpl implements MyFactory {
INSTANCE;
private final MyObject myObject = buildMyObject(); //I want to instance control this
private MyObject buildMyObject() {
return new MyObject();
}
public MyObject myFactoryMethod() {
return this.myObject;
}
}
I tried calling the factoryMethod in a test case in parallel fashion using testNG, and multiple invocation seem to return the same hashCode.
#Test(threadPoolSize = 10, invocationCount = 600, timeOut = 100000)
public void test_instanceControlledBehavior() {
final MyFactory f1 = MyFactoryImpl.INSTANCE;
final MyFactory f2 = MyFactoryImpl.INSTANCE;
Assert.assertEquals(f1.myFactoryMethod().hashCode(), f2.myFactoryMethod().hashCode());
}
Is this the correct way of implementing the behavior? Is there a better way I can instance control 'MyObject'?
I've been trying to code something so that:
Class 1 creates an instance of Class 2 (Class t = new Class() ). That instance can be used in Class 1,2 and 3.
I've been looking around for a bit and found the "Singleton Pattern". I don't understand how I implement this into my code though and a fair few of the sources are all saying different things...
Thanks for any help, much appreciated :)
Singleton Example: If you have a Class Phonebook and you want every Class of your programm refer to the same Phonebook. You would make the Class Phonebook a Singleton-Class.
In other words: The Singleton Pattern is used, to asure every other Code is refering to the same Object of the Singleton-Class.
class Phonebook {
//Make the constructor private so no one can create objects, but this class
private Phonebook() {
}
// to static members to hold (m_Instance) and get (getInstacnce) the Singleton Instance of the class
private static Phonebook m_Instance;
public static Phonebook getInstance() {
if (m_Instance == null) {
// first call to getInstance, creates the Singelton Instance, only we (Phonebook) can call the constructor;
m_Instance = new Phonebook();
}
return m_Instance; //always the same Instance of Phonebook
}
... // Members of the Phonebook (add/getPhoneNumber)
}
Every part of the software, will get the same Instance of the Phonebook. So we can register phonenumbers, every other class can read.
...
Phonebook l_Phonebook = Phonebook.getInstance();
l_Phonebook.addPhoneNumber("Yoschi", "01774448882")
...
// somewhere else
Phonebook l_Phonebook = Phonebook.getInstance();
Phone.getInstance().call(l_Phonebook.getPhoneNumber("Yoschi"));
Here is a link to the description:
http://en.wikipedia.org/wiki/Singleton_pattern
A sample code will be
public class singleton
{
public static singleton _obj;
private singleton()
{
// prevents instantiation from external entities
}
public static singleton GetObject() // instead of creating new operator, declare a method and that will create object and return it.
{
if (_obj == null) //Checking if the instance is null, then it will create new one and return it
//otherwise it will return previous one.
{
_obj = new singleton();
}
return _obj;
}
public void printing(string s)
{
Console.WriteLine(s);
}
}
This is a c# code but the concepts are the same as java.
Let's say I have a class called Object and a thread called ObjectCreator that manages the creation of an Object. For the sake of simplicity, Object has attributes: objectNumber and objectName.
If I were to create an instance of Object called instance, it would be held by ObjectCreator. Now let's say I needed another thread (let's call it ObjectChanger) to be able to see and manipulate instance; does it make sense to turn instance into a static Object?
I've managed to see results by making instance static so now I can do something like:
ObjectCreator.instance.getName();
Where getName() is a method of Object. From what I've read from answers to similar questions, static things are evil and there's always workarounds. One suggestion I've read is to pass instance to ObjectChanger as an argument for its constructor but what if instance wasn't created yet at the time I need to create an ObjectChanger?
Perhaps this question is more about OOP concepts than multi-threading or it may be a duplicate so forgive me but I'm quite lost here.
EDIT: To address frankie's and Jim's suggestions, here are some code snippets:
Object:
class Object
{
private String objectName = "Something";
private int objectNumber = 1;
public synchronized void changeNumber(int newNumber)
{
objectNumber = newNumber;
}
}
ObjectCreator:
class ObjectCreator extends Thread
{
static Object instance;
public ObjectCreator (Object something)
{
instance = something;
}
static void createObject()
{
...
}
static Object getObject()
{
return instance;
}
}
ObjectChanger:
public class ObjectChanger extends Thread
{
private Object currentInstance = null;
private int instanceNumber = null;
public void run()
{
currentInstance = ObjectCreator.getObject(); //If I were to make getObject() non-static, this line churns up an error
instanceNumber = currentInstance.getObjectNumber();
currentInstance.changeNumber(2); //valid?
}
}
If you want a thread to obtain access to an object not created within it, you must ensure that said thread has a path of references which it can follow, leading to the new object.
Consider the following code, with no threads involved.
class MyObject { /* ... */ }
interface MyObjectProvider {
MyObject getMyObject();
}
class Creator implements MyObjectProvider {
private MyObject obj;
/* ... */
#Override
public MyObject getMyObject() {
return obj;
}
/** Invoked at some point in time. */
void createMyObject() {
obj = new MyObject();
}
}
class Consumer {
private MyObjectProvider provider;
Consumer(MyObjectProvider mop) {
provider = mop;
}
void consume() {
// At some point in time...
MyObject o = provider.getMyObject();
}
}
Example of a program:
public static void main(String[] args) {
Creator creator = new Creator();
Consumer consumer = new Consumer(creator);
creator.createMyObject();
consumer.consume();
}
When you add threads to the mix, some code has to change, but the struture is the same.
The idea is to run the Creator in a thread, and the Consumer in another, as you've pointed out.
So, in short, these are the things you should be looking into:
Concurrency control: look into data races, synchronized, mutual exclusion, and their friends. Start here.
wait and notify, if the Consumer should wait for MyObject to be created. Look here.
When you have a nice grasp on these concepts, you may look into the volatile keyword (watch out for its pitfalls), and the java.util.concurrent package which provides better concurrency primitives, concurrent collections, and atomic variables.
You can put your objects in a list structure like Vector and store them in the ObjectCreator. Add a getter method to ObjectCreator which will accept an index of the object to be received.
This is just a skeleton showing the basic structure. Error handling is left as an exercise :-)
public class MyObject { ... }
...
public class MyObjectCreator {
private Map<String,MyObject> createdObjects = new HashMap<>();
public MyObject makeNewObject(int objNum, String objName)
{
MyObject o = new MyObject(objNum, objName);
this.createdObjects.put(objName,o);
}
public MyObject getObject(String objName)
{
return this.createdObjects.get(objName);
}
}
...
public class MyProgram {
public static void main(String[] args)
{
MyObjectCreator oc = new MyObjectCreator();
MyObject mo = oc.makeNewObject(10,"aNewObject");
...
MyObject o = oc.get("aNewObject");
...
If you only want to change the values of the fields of your class, you should just pass the object into your newly created thread. Then there is really no need to keep a static reference around in a holder class.
But as commented already, we need a bit more information to get to what you want to do with your object and thread.
Why cant you just make an getter in the ObjectCreator class that retrieves said Object?
ex: ObjectCreater.getMyObject()
EDIT:
I think you're looking for something like this if Im not mistaken:
public class ObjectCreator{
ArrayList<Object> children;
public ObjectCreator(){
children = new ArrayList<Object>();
}
//returns back index in children array (for accessing from other threads)
public int createObject( whatever params here ){
Object o = new Object( params );
children.add(o);
return children.size()-1;
}
}
since I dont know much about the problem you're trying to solve, Im not sure if it has to be thread safe, if you want these objects mapped, or accessed differently, but Im confused where all the confusion about static is coming...
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;
}
}