My application requires access to certain Objects throughout the application. These objects are populated through the DB.
I would like to populate the objects on server startup , and then in the application on a need -to -do basis.
What is the best pattern to implement this, i have read about the Registry pattern, but not sure that is exactly what i want.
I am also using Spring 3.x in my application , is there something in Spring that can help me?
Since you say you are using Spring. The best solution is to use FactoryBean. What this class allows you to do is create a bean of whatever type you like and return it to the Spring context. Spring will manage this bean and expose it to other beans by making it a singleton. An example:
public class MyObjectFooFactoryBean extends SimpleJdbcDaoSupport implements FactoryBean<ObjectFoo> {
private String query;
#Override
public String getObject() throws Exception {
return an ObjectFoo here using SimpleJdbSupport (Because I also extended SimpleJdbcDaoSupport)
}
#Override
public Class<?> getObjectType() {
return ObjectFoo.class;
}
#Override
public boolean isSingleton() {
return true;
}
}
Above does two things. 1) Extends SimpleJdbcSupport which allows you to have access to the databse, and 2) Implements FactoryBean which returns the object to Spring's context. After this is done, you can #Autowire it or use it in the xml file.
Are you sure your application really requires that?
Global objects are artifacts from the past of programming, they shouldn't exist anymore in a proper object-oriented environment, and are usually considered an anti-pattern.
Surely you don't need to access these objects everywhere. Why don't you just inject them in the classes that need them? If you use Spring, that's even easier, only have to declare the dependency in the context.
If there are many of these objects that you need, you could wrap them all in one holder class, that you inject as needed.
When I use global objects I usually wrap each object in a singleton pattern. It's the simplest solution, and you can even lazy load it only when needed.
In some cases this is a very valid pattern. For example in any iphone app you have a singleton Application object which is accessible globally through a public static method
This can get a bit hairy if your application is deployed in multiple servers (each with its own VM, thus having singletons as static fields will get messy, and having context-based attributes won't work unless the servers are set to replicate and that's unreliable as well). I'd recommend using a database memory table instead, or some other sort of server-independant memory cache. ( http://memcached.org/ for instance)
What about defining a global object to store these information? You can control access to this object. If you want to monitor this object's state, you can use observer patterns.
Related
I am confused.
Spring's default bean scope is Singleton. That means that once you define a bean of your class, every time a new "message" comes in, it will be processed by the same instance of that class.
But that also means that you cannot have mutable instance variables in that singleton bean because the next call of a method of that class will see data from past calls..
Example:
Calculator is my bean (singleton)
public class Calculator {
private List<String> operations = new ArrayList<String>();
public void calculate(String op, double val) {
operations.add(op);
// do some calculations
}
public List<String> getAllOperations() {
return operations;
}
}
Here's the client (useCalc is invoked many times!):
public class CalculatorClient{
#Autowired
private Calculator calculator;
public void useCalc () {
calculator.calculate("Add",100);
calculator.calculate("Div",100);
calculator.calculate("Diff",100);
List<String> allOperations = calculator.getAllOperations();
// Do something..
}
}
So let's say CalculatorClient useCalc gets called several times with different operations..
eventually operations in Calculator will contain all of the operations ever done on that calculator.
So the question is this:
Is this Spring's limitation - not being able to effectively share information between methods within a class? And if it is so, how to share that kind of information between methods?
I know there is the prototype bean scope. Is that the only solution in this case?
BTW, prototype is not a solution here because with prototype a new class will get instantiated with every call to calculator:
calculator.calculate("Add",100); // New
calculator.calculate("Div",100); // New
calculator.calculate("Diff",100); // New
And since Singleton is the default scope - aren't developers inadvertently introduce such bugs?
A common use case for singleton beans are to inject services into other objects.
Example, to provide an object a service to connect to the database, you "autowire" a database connection bean.
You don't want to create a new instance of the database every time, so singleton beans make sense.
Usually, the object itself that uses the autowire is a singleton as well (in a web app, the Controllers are also created just once, you don't want to create a controller for every request).
aren't developers inadvertently introduce such bugs?
Since the idea is to process several requests concurrently, all of those objects are usually already coded without having common state shared using instance variables.
This is not a "limitation", but rather a default for the most common use case.
I know there is the prototype bean scope. Is that the only solution in this case?
It sounds like a good "solution" to this, in that case a new bean will be created. Note that it would not make sense to autowire a prototype bean into a singleton since in that case there will only be once instance anyway.
Another possibility more commonly used is autowiring a singleton bean that acts like a factory, then ask that factory for a new object each time you need one.
The factory can be a singleton since you don't want more than one factory, but it would then return new objects in every call to its "create" method.
So in your example, you could do something like
#Autowired
private CalculatorFactory calcFactory;
public void useCalc () {
calculator = calcFactory.createCalculator();
calculator.calculate("Add",100);
calculator.calculate("Div",100);
calculator.calculate("Diff",100);
List<String> allOperations = calculator.getAllOperations();
// Do something..
}
}
There's a lot of conflation going on here. Let me try to unravel the premises.
The whole point of dependency injection is to make it so that you don't have multiple instances of a critical application service, which would lead to things getting out of sync or result in erratic behavior (e.g. multiple database connections, multiple access points to a JMS queue, multiple ways to query a database, etc).
It is not a mandate to make everything injectable.
If something is not inherently reusable, or you would not gain anything from registering it in the component scan, then there is no reason to make that thing either a bean or a component.
It is fairly reasonable to assume that beans shouldn't store state, but that doesn't mean that something else couldn't store that state on its behalf. For instance, you could put those operations into some other backing store as opposed to in-memory, and you'd still be able to keep the state of operations you've done.
The big thing that I'm seeing is that you've kind of implemented your Calculator class half-thinking that it was a bean, and half-thinking that it was newed up somewhere. By having that list in your class, you're subconsciously forcing yourself to hold onto the state in any instance created, which violated the inversion of control principle - you don't control the lifecycle of the object.
To get around this...you have a few options available.
Change how you're storing the state of your operations. Put it into a SQLite database or a file or somewhere that isn't dependent on an instance maintaining it.
Inject your own. You can create a bean that is of type List<String>, and require your Calculator to inject it when it's needed.
Don't create a bean. You can new this and Spring isn't really going to fuss at you. It'd make it harder to test, though.
The first two approaches abstract away the notion of storing the data from an operation and reading the data from the operations. You can either read from the injected operations bean or from the SQLite database or from the flat file to get the result of operations that you want.
I'm writing a database manager layer of a web service.
I have to decide ho to implement my library: this is the situation.
I have a class, PersistenceUnit:
private static RazoooCore rc;
private static DBInstance db;
protected ODatabaseDocumentTx getDb(){return db;}
protected RazoooCooore getRc(){return rc;}
public static void startPersistence (){
//here I get an instance of rc and db
}
that start my db service and allow me to connect to it. What I want is to write class that implement persistence method, like addUser(...), or deleteFile(...) and so on.
My doubt is how to realize these method. Because I have two big classes of operations (one on users and the other on files) I thought to create to class (User and File) and to implement public static method on them, or, and is the same, create two singleton.then the application layer will have to call method without having to create and destroy object each time.
Is this a good way to realize my layer? Is, in this way, well handled concurrency, or is there a better way (perhaps a pattern) to maximize performance and multithreading?
Certainly this is not a memory-bound layer, because upper layer doesn't have to continuously
create object.
Thank you
There were lots of discussions about if an object should (or not) be responsible of persist itself, this is, should an User class have a Save method? Well, it depends. However, currently we hardly ever see that pattern.
I think the persistence logic has to be in a data access layer, probably in repositories (UserRepository and FileRepository). And this has nothing to do with neither performance nor multithreading because both issues (performance and concurrency) are in the database.
That´s my opinion.
In android there is a mechanism of ensuring that only one instance of a class is available to the whole application. This can be done by deriving that class from Application.
Can some thing similar be done in servlets? I want to initialize a class when the application is deployed. This class should have only one instance. So that what all the servlets can access it.
I came to know that you can store your data in the servlet context's hashmap. But I don't want to do that. I want to write my own class with its functions. How should this be done?
I think what you're after is simply a singleton.
This is best implemented by defining an enum with a single instance. (Note that enums allow you to have member functions just as classes.)
public enum YourSingleton {
INSTANCE;
// Your methods...
}
and then you access it as
YourSingleton.INSTANCE
So, create whatever class you want with its own functions or whatever you like, and put that in the ServletContext at startup. You can use a ServletContextListener to initialize and remove it. What's limiting about that?
Use singleton pattern so the first call to instance method (say YourClass.getInstance()) will create the instance and it will be reused across the application.
I'm writing a small web server, and it takes a configuration file with all sorts of different options: how many threads to run, which class deals which each file extension, which file to display by default and so on and so forth. To represent this, I'm parsing the config file into a Configuration object which contains all these settings, and the main class holds this object.
However, the config data is required on almost every level of the server - classes within classes within classes...
My question is, what is the best practice to use here? Should I give the config as a parameter for many many classes and pass it back and forth? Should I make it a singleton? Is there another solution I don't see?
Use Guice! Guice is a dependency-injection framework which effectively replaces your use of the new keyword. You define your object bindings in a Module like this:
bind(Configuration.class).to(MySpecificConfiguration.class);
bind(WebServer.class).to(MySpecificWebServerImplementation.class);
And then, instead of newing up WebServer directly, you just ask Guice to do it for you:
WebServer ws = Guice.createInjector(yourModule).getInstance(WebServer.class);
Which will magically create MySpecificWebServerImplementation for you. If MySpecificWebServerImplementation is defined as follows:
public class MySpecificWebServerImplementation {
#Inject
public MySpecificWebServerImplementation(Configuration configuration) {
}
}
Then MySpecificWebServerImplementation will automatically get given the configuration and you don't have to worry about passing it around.
Passing an instance of Configuration around adds a lot of unnecessary clutter to your code. A Singleton is a good idea or add some sort of Manager class that provides all those shared resources, like configuration data.
If you go for singleton, consider implementing the enum pattern:
public enum Config{ DATA;
private int value1;
private int value2;
private int value3;
public load(File configFile) {
// some magic to store the values
}
public int getValue1() {return value1;}
public int getValue2() {return value2;}
public int getValue3() {return value3;}
}
You can use it everywhere in your code:
int property = Config.DATA.getValue1();
Although Singletons are no longer favored by many professionals for various reasons - I think there is still a good use case to use a Ssingleton`.
However - ask yourself if the webserver's requirements really require a single common configuration for all aspects of the server. And if yes - how likely are they to change soon?
For example - lets say your server hosts 3 web sites. And now you are asked to put bandwidth limitations on one of them - how will you configure this?
I really favor a good singleton - although you have to mind the whole thread-safety issue when initializing it in a multi-threaded environment (Although it sounds like you won't have this problem as you won't have multiple threads before initializing it.
Keep in mind that singletons live within a ClassLoader and if you have multiple ClassLoaders (e.g. for each .war you load) you will have multiple copies of this "Singleton".
Consider all the aspects of your server, and if it is really simple - A Singleton will save you a lot of headache - and will make the code much more maintainable and readable.
As mentioned already in one or two of the answers - dependency injection is a good alternative to Singletons - they help you make your JUnits easier.
One note about JUnit, I understand (didn't try it yet) that Mockit can allow you to replace an actual implementation during a test run, so you can still create different JUnit test cases for different scenarios without modifying your Singleton to be testable.
Making it a singleton seems like a reasonable solution. I think it would be a mistake to pass the config around as a parameter to other other classes constructors or method calls as this will tend to pollute the method arguments and make them unnecessarily complex.
If you do decide to make a singleton, then I'd recommend devising a mechanism whereby you can inject new instances of the config into the singleton class so that the singleton doesn't make your unit tests very hard to run.
If you're doing this in Java, I would place all the configuration in Spring and then either use the Application Context to lookup the settings or simply inject them into your beans. Spring excels at this sort of thing.
We have your properties set as system properties. These are accessed by a SystemProperties class. This class is final with a private constructor, the properties are accessed via static methods only, so it is technically a Singleton. It is itself contained in a commons.jar every other project is depending on.
So there is no need to pass anything around as the settings are available directly where you need them.
I definitively would make the configuration holder class a Singleton! I's the classical use case for a Singleton instance.
Configuration not, but It's good to have one singleton object ServerManager. Too many globally accessible objects are are little bit confusing. Configuration should by owned by "component":
ServerManager.getServerManager.getConfigurationComponent(Configuration.class);
ServerManager should create and read configuration object at start time. Save and close it before leaving.
If you use it more than once in any class store it as private final field.
I have used this a lot. I do multiple installations of products, and they are not always in the same place. However the installation, integration, and implementation of the product is usually the same. So in order to compensate for this, I write a config properties class, that looks at a config.properties file. You would go in and modify the properties file first to the locations, values, etc... of what you need before hand. Then compile the class with the config class, and carry that through with the application.
Example below. config.properties file
import_dir=c:\\temp\\test\\import
export_dir=c:\\temp\\test\\export
system_dir=c:\\temp\\test\\system
username=mainman
role=admin
domain=
server=
hostname=
etc...
I then created a class inside of my class.
public static class Config {
private static Properties defaultProps = new Properties();
static {
try {
FileInputStream in = new FileInputStream("config.properties");
defaultProps.load(in);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getProperty(String key) {
return defaultProps.getProperty(key);
}
}
I am sure you could also create a stand alone class, but this works as well.
Then inside of my method, or in the main class I get the values I need and assign them to whatever I need. I can then pass them to the corresponding method that needs them.
domain = Config.getProperty("domain");
server = Config.getProperty("server");
hostname = Config.getProperty("hostname");
It is pretty cool!
I also use this on multiple OS's.
Consider a web application with business layer and data access layer. So, every request has to be passed through these two layers in order to get processed.
Since there would be frequent requests coming in, it is not wise to create a new business and data access objects to process each and every request. In this case, usually I tend to go for Singletons of business and DAO.
But I hear lot of problems in using Singleton pattern, as many suggest against the pattern (mainly because its global). In that case, what would be the correct design strategy for the scenario I described above?
Service Objects should be Singleton.
You can use Spring to maintain singleton service objects for you.
The usual strategy used in such cases is to write the business services and data access objects not as singletons but as simple POJOs. And then use a container to manage the scope of the classes. Some examples of containers are Spring and Guice. You can even write your own container if your requirements are simple.
This way you get the benefits of the singleton pattern without its disadvantages (difficult to mock and test, etc).
A simple example:
public class PersonService {
public Person getPerson(String id) {
//find and return the person
}
}
public class PersonServiceSingletonFactory {
private PersonService service = new PersonService();
PersonService getInstance() {
return service;
}
}
I don't think that writing singletons on Servlet is good idea, you can create your business logic on ServletContextListener it will assure that only one instance of object will be run in container and it is thread-safe. you can access it the way #abhin4v explained. Unless you are using Spring framework this is what you need to do.
Hope it helps.