I'm in the middle of creating an Android application with multiple tables inside of my database. The database is going to be constantly accessed, but with that said I've stumbled upon the idea of a singleton from http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html
Would it be advised to try to make a database a singleton so that I never have conflicts?
EDIT: In response to the first comment. I have an SQLiteOpenHelper class that I believe I can structure into a singleton.
It depends on your application and design. You can make a class singleton if it only creates a database.
But if you make singleton a class which executes query, you have to make sure that it doesn't gets called while the first query is executing. So a locking mechanism or queuing will be required then.
Related
I'm making an Android app that will have the timetables of a local bus.
There are more than one timetable, the one that will be use depends on the day.
If it's a holiday I must use a special timetable, so I want to know when is a holiday and when is not.
The thing is that I'm creating a class that will handle this, it will try to retrieve information from memory or from a web api. Then some other classes will be able to communicate with this class, but it doesn't seem necessary to me to have more than one instance of this class, I could create just one instance and share it with the rest of the classes.
Could this class be a Singleton or it would be better if I create a normal class ?
In your case (retrieving info from memory), definitely avoid using a singleton class because it will highly likely be tied to your Activity context.
Your class will have a static reference to a class, therefore
it will be kept in memory when not needed.
singleton may be reinstantiated, or may use obsolete instance, with new instations of activities. You will lose control of the current variables.
diffent instances of the same activity class are highly likely to conflict with this class.
Examples of the same activity class several instantiation:
Change device orientation.
Running app from the webbrowser's, Google Play, file browser intent.
Besides, at some point, when you add functionality based on user reviews, your app will grow, you are likely want to refactor your class, break it into subclasses, put some of its methods into separate threads. It will no longer be easy to do.
It might seem fun while the app is small, and untested, but later, in Android specifically, you will run into a nightmite with unpredictable and hard to detect errors.
Because of Android's special way to recreate activity class, through onCreate, onResume etc. you will run into a nightmare, when the app will start living its own life.
You will no longer be able to rely on the assumption that the current singleton instantiation actually belongs to your current activity.
You may swap between orientations or run your app from different entry points (launcher, recent apps, google play), and it may reuse the variables actually prepared for a different activity instantiation.
If you need only one instance of the class, just create one instance of the class in the onCreate method - and that will make the app much more manageable.
One of the main advantages a Singleton class brings you is the fact that you are sure to have one and only one instance of an object doing some thing, and that it is instantiated only once (preferably at a specific point of your application, for instance at startup or only after certain other operations have been performed)
An example could be for instance a cache implementation: you want to make sure that all classes that need a certain cache read and write from the same object, that maybe is created and filled with information at startup time.
Your does not seem to be the case, unless you fetch the information you need when your application starts and then you keep them memorized for some reason: in this case you want to make sure your information is fetched one and only one time, to avoid wasting memory and elaboration time. Also, a Singleton is fine if you need to do some kind of operation when your class is instantiated, like opening a connection that then stays open.
On the other hand, if you just need a class with some method to call some external apis or database and you don't need to memorize any information in it, there is no reason to initialize a singleton.
If this is your case, why don't you try some static class/methods? They can be called like normal methods directly on the class with no need to instantiate objects or keeping a state, saving memory and avoiding side effects.
I have a Spring application that is controlled with an API that we need to be single threaded, but I can not figure out how to accomplish this. The application is a re-factoring of an app that is single threaded. They want the same basic design for the new version, while using our new programming methods (i.e. Java, Spring, etc.) and adding extra functionality.
There is an API resource to start the application:
#RequestMapping("/start")
public String startProcess(){...}
If this gets called twice then the application will start another thread. We want to stop this from happening. But, we still want the stop API resource to work:
#RequestMapping("/stop")
public String stopProcess(){...}
The app has a typical Spring structure:
#SpringBootApplication
public class MyApplication{...}
#RestController
public class MyController{
#Autowired
private MyService myService;
...}
#Service
#Transactional
public class CarolService{
#Autowired
private MyDAO myDAO;
...}
#Repository
public class myDAO{...}
How do I make sure that there is only one instance of this application running at a time? Please Help! And, thanks in advance!
You have actually two different problems: making your API single-threaded and making sure that there is only one instance of this application running at a time.
The solution is conceptually the same: you have to synchronize on some mutex. But it's much easier to do in the first case than in the second.
To make your API single-threaded you'll need to synchronize on something. If you have just one controller, just make API methods synchronized. If you have more than one controller, you'll need to create some application scope bean, inject it in every controller and synchronize on it. In old times there was also something like SingleThreadModel, but I think it was deprecated. Haven't seen it around for a few years but I won't be surprized if Spring would have a way of setting it somehow.
Making sure that there is only one instance of this application running at a time is much harder. You basically want to prevent anybody to start several copies of the application in parallel. One of the way to achieve this is to have some central shared resource like a database. On start-up the application will try to "acquire" the mutex by creating a record in some table (which would allow at most one record). If the record was created successfully, the application starts normally, if not then fails. You'll need some mechanism to detect stale mutex record - probably as simple as saving the timestamp in the mutex record and constantly updating it via scheduled task (heartbeat).
We recently had a similar task in an application running many instances of many microservices. We needed exactly one microservice to regularly execute certain maintenance task. We solved it by synchronising over a central MongoDB database. Microservices try to acquire the mutex by creating a document in a database collection. By design, at most one document may exist in that collection and the microservice which created the document performs the regular task and removes the document at the end. The collection is configured with an automatic clean-up so if the microservice failed to remove the document for whatever reason, it will be removed automatically by the database.
I'm relatively new to Android programming and I have little to no experience with SQL and its interaction with Java altogether, but I couldn't find the answer I was looking for either in tutorials or Google's developer pages.
I'm wondering how I can create a database in Android to store a variety of String and int variables without creating duplicate databases. I understand the schema and contract class concept presented by the development page, but I don't understand how I am supposed to call a class method so that only a single database is created (preferably at first app launch) without several instances being created.
My main question: What sort of setup is recommended to create a database that can be referenced from other classes, exists from the very first launch of the app, and remains private (although to be honest it's not a huge priority)?
but I don't understand how I am supposed to call a class method so
that only a single database is created (preferably at first app
launch)
In Android, database is created only once and then whenever you will try to perform CRUD operations and selects statements, always you will have only one database created. It's same for table(s) in database. Once table(s) are created, they won't be created again (so be careful if you'll add new columns to table during implementation if table was created before without new columns1). Moreover if user explicitly will delete application data - only in this case, database and table(s) will be created again because they were deleted.
What sort of setup is recommended to create a database that can be
referenced from other classes, exists from the very first launch of
the app
In the moment when you'll call for example getWriteableDatabase() or getReadableDatabase() database and table(s) will be created - only at this time! Only once. No more (except1. After that, whenever you'll try to attempt to read or write from / to database your database will be opened with specific permissions (read-write or read-only - it depends how which method you called) and you can perform actions.
without several instances being created.
Database is only one - it's not duplicated (physically), absolutely but when application logic is not designated correctly, there may appear multiple instances of database and this fact is not very good and usually a nightmare of many beginners with Android and SQLite.
But solution exists and it's not hard to implement -> Singleton. Design pattern Singleton is "pretty cool tool" for our goal - ensure that only one instance of database will be ever created.
Here is implementation of Singleton itself:
public class DataSource extends SQLiteOpenHelper {
private static DataSource instance;
public static final DataSource getInstance(Context c) {
if (instance == null) {
instance = new DataSource(c);
}
return instance;
}
}
1 If you added new columns to table at the time when database and table were created before (how i mentioned above the're created only once) it may cause application exception so exactly here you have to clear application data or implement onUpgrade() method.
Try using an ORM like ActiveAndroid. While not recommended for extremely complex apps, using an ORM will make using and managing a database much easier for someone without much database experience (and can make your code more readable as well).
When I did my first SQLite DB in Android, I used this site to get me trough the basics.
To answer your question, take a look at the DatabaseHelper Class. You will see that you have to specify a DB name (filename).
private static final String DATABASE_NAME = "commments.db";
Android will automatically create the DB if it's not existent (newly installed app) and will reuse it if it's there. As long as you use always the same file (and don't mess up the tables), your DB will remain intact.
Also, for security, the DB is stored in the app's data. Not accessible with a file browser (unless you are rooted). You can download the DB via adb if you really need to. There is tons of documentation on how to gets apps private data.
Hope this helps!
I'm starting with Android and wonder if background Task like DB reading and saving are always encapsulated in private classes?
I mean, at the moment I have:
private class SaveToDB extends AsyncTask..
private class ReadFromDB extends AsyncTask..
public void onButtonClick(View v) {
new SaveToDB().execute();
}
And so on. This way, I always have to create a new object if I want to execute background tasks. Is that the correct way?
What I wonder is that all my private classes are "actions" itself, not really objects. As they are named eg save or read which naming normally applies to methods by convention, not to classes.
Moreover, in case I'm doing it right: is it good practice to neast the private classes inside MyApplication Activity? Or should I refacter them out into own separate classes?
You could write a service to handle all the background content management. So, when you want to save, you just message the service and tell it to write data. This is much more complicated. For simple things, you can do it exactly as you are currently.
EDIT:
Also, as Ian pointed out, take a look at the new database interfacing classes post 3.0.
If you are firing of async tasks to interact with a sqlite database, then its not the best way to do things these days, you should check out cursor loaders instead.
http://developer.android.com/guide/topics/fundamentals/loaders.html
http://developer.android.com/reference/android/content/CursorLoader.html
Once you got your head around them they are much easier than firing off async tasks, infact they build on top of async tasks to address some of the issues you describe and are tolerant to configuration changes.
I highly recommend to move away from AsyncTask (for db access) and use the Loader API instead.
Its backported in the compatibility package so you can use them in older versions prior to Honeycomb.
Not always.
For example, if you've got a task that is to be used by different activities (I'm not talking about sharing the same instance), you will want a public class so you don't write it several times.
If you only use that (class of) task in one place, private class might help keeping your code cleaner.
It is a correct way for using AsyncTask, which isntance you can execute once.
Class Name can be DbSaver isntead of SaveToDb for instance which is more readable.
If that class is used only one Activity you can nest them, why not. But if you have task which is executed within different Activities, it is a good idea to create his own file.
It is good design to loosely couple your database access from your UI code. One way to avoid having to create a new object every time would be to make the database access classes a singleton and just return the instance of the class whenever you need to make a transaction.
To your last question it is a better idea to move the database management to its own class so that it can be accessed across several activities. If you do it all in a private class then what happens when you have a new activity that need s database access?
In the database, I have a definition table that is read from the application once upon starting. This definition table rarely changes, so it makes sense to read it once and restart the application every time it changes.
However, after the table is read (put into a ResultSet), it will be read by multiple handlers running in their own threads.
How do you suggest to accomplish this?
My idea was to populate a CachedRowSet, and then create a copy of this set (through the createCopy() method) for each handler every time a new request comes.
Do you think this is wise? Does this offer a good performance?
Thanks.
It may be better for you to use the singleton pattern. This would allow you to create a single class that all of your threads could access to get the object that they needed. This could also allow you to not have to shut down your application whenever changes are made. One way to accomplish this is to have a class where you have get and set methods for the information you need. And another class that will give out references of that object.
The class that gives out references could have a private constructor, and a getInstance method that will return a reference to itself to ensure that only one exists. This would also give you some other options regarding what you can do when things change.
Ok, if you control access to the resultSet, and you don't care to update the result set until you restart the application, then i would suggest wrapping the CachedRowSet in a custom class. One possible way to do this is to have a wrapper class that is a singleTon and provide it with getter methods so that other threads or classes for that matter can access it. That way you remove the need to make a copy and remove the dependency on CachedRowSet implementation. Creating a copy would cause unnessary overhead. Imagine, in the way you described above, if you had 1000 threads accessing your result set, you would call createCopy() 1000 times thus creating a 1000 copies of the same resultSet.
I think it is a pattern to read the configuration table into a static data structure (ConcurrentHashMap) and then let the threads to look it up.
You can ensure that there is no write race at startup by populating the reference map from a Servlet.init() - it is guaranteed to execute once per servlet.