I'm a bit confused about my new class type I've written.
My class would be used to serve question and options pulled from database for about four thousands concurrent users. (Because exam will start at the same time for all)
Now what class type should I use for making it work faster.
Would it be good if I make it static?
public static List<Questions> getQuestions(String qType){
List<Questions> objListExamsExt = new ArrayList<Questions>();
....
....
....
while (cursor.next()) {
Questions objExamQuestion = new Questions();
objExamQuestion.setQuestion_id(cursor.getString("question_id"));
....
....
....
objListExamsExt.add(objExamQuestion);
}
return objListExamsExt;
}
A case where a static class might be a good idea is when you want to collect related pieces of functionality, but you don't need to have any internal state in any object.
Normally you can create a static Utils class containing a whole bunch of related functions that are accessed outside the context of any specific object instance
A singleton allows a class for which there is just one, persistent instance across the lifetime of an application.A singleton class might be useful if you have some kind of shared resource, such as a database, an in-memory cache, or maybe some specialized piece of hardware like a robotic arm. Many parts of your program might want to use this resource and you might want to have all access to the resource go through a single point. A singleton isn't always the only way to handle these situations, but it's one of the few places I think a singleton might be a good choice.
In your case if getQuestions() is used in multiple places in your application then you can group it together inside a static Utils Class.
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.
In an Android application, is it bad practice to store objects in static fields in these cases?
Application data. Is it bad to keep application data in static variables in a class while the application is running? Currently, I'm storing the data in an instance variable in my Application class. Then classes that need the data can obtain the data from the Application.
Context's etc. Is it bad practice to store a Context (e.g. a reference to an Activity or an Application) in a static field? This can be used in a class that needs e.g. a LayoutInflater or resources. Currently, I am passing the Contexts to methods needing them as arguments.
Yes and Yes. :)
Static Fields. There are a lot of problems with excessive usage of Static fields. Not only they are slower to access by an interesting margin, but also they are prone to be destroyed overnight by Android, and it's usually hacky to check for their references all over the place or fill your getter/setters with if (sSomeStatic == null) { return new SomeStatic()}. It's ok to store a static reference to a class called (for example) ApplicationData where you store some values, hey, we NEED some globals every now and then, but it's so easy to abuse it, that I frown every time I inspect new Android devs' source code.
Yes, store your Application instance in a singleton pattern and use it, but don't add 200 static fields to your Application implementation just because you can do YOURAPP.getInstance().SomeLazyValueYouAddedHere();
That is bad. It leads to bad practices and it will be slower than having a good design where you access hard references.
I could go on forever but there are a lot of StackOverflow discussions (some heated!) about this. If you are here, I'm assuming you're asking for experience; I've been doing Android for a couple of years in different projects and my experience has always been that the less Static, the merrier.
Now the context… oh the Context. Don't store the Context in a hard reference, ever. Or you will leak memory. An activity has references to View and a multitude of other things. If you store the Context, you're storing the activity and things go bad from there. Learn to pass the Context around, use the Application Context whenever possible and if you need to pass it around, do it for very good reasons. Most of the time the App context is enough for getting resources, strings, etc.
If you're going to store the Context, always store context.getApplicationContext(); Never store a static activity context. You can google this too and StackOverflow has some good answers.
If you can afford one and only one Android book, get the BNR one. Even though Android may release new SDKs every now and then, the concepts are completely valid and the patterns the author uses are the right way to deal with Activities, Contexts, Fragments, etc.
UPDATE Your Application should look like this:
public class YourApp extends Application {
private static YourApp sInstance;
public YourApp() {
super();
sInstance = this;
}
public static YourApp getInstance() {
return sInstance;
}
}
And in that case, yes, you are getting the same Static reference to the same App Context.
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 some code that I am maintaining I noticed two different ways to register a shared preference change listener:
(1) The straightforward approach, in which the class containing the registered member function implements SharedPreferences.OnSharedPreferenceChangeListener.
preferences.registerOnSharedPreferenceChangeListener(mImageView);
(2) The indirect approach, in which the the class that could have contained the registered member function, prefers not to implement SharedPreferences.OnSharedPreferenceChangeListener for some reason, and instead opts for defining and instantiating a whole new class dedicated only for this listener:
SharedPreferences.OnSharedPreferenceChangeListener mPreferencesListener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// do here what's needed to do
}
};
....
preferences.registerOnSharedPreferenceChangeListener(mPreferencesListener);
Both work well but now I am wondering: Is one approach preferable over the other?
Are there circumstances in which only one of these 2 approaches could actually be used?
This is up to implementation, in terms of maintainability some people may found one or other way better for their intentions, some people just go further thinking of readability, natural medicine, etc.
In the other hand of course you may want to prevent any leak and garbage collection issues, said if member created mPreferencesListener is accessing any of the enclosing instance methods you may run in some issues, as a good citizen you should unregister your listeners after you know that you will not be using them (e.g. onPause, onDestroy, etc.) and opt for static inner classes instead of member inner classes and be cautious when anonymous and local inner clases access enclosing instance methods/properties.
Finally is worth to mention that as for now SharedPreferencesImpl uses a WeakHashMap for its listeners.
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.