This is a question about my next question: Performance for Android threads
I am having difficulty moving my head around synchronized methods for my application.
I check sensors and store sensor values in arrays when they change
float[] accelerometerMatrix = new float[3]; float[] accelerometerWorldMatrix = new float[3]; float[] gyroscopeMatrix = new float[3]; float[] gravityMatrix = new float[3]; float[] magneticMatrix = new float[3]; float[] rotationMatrix = new float[9]; class InsertHandler implements Runnable { public void run() {
Every 10 ms, my application will take the current sensor values (from arrays) and insert them into the database using one stream executor. Thus, the onSensorChanged method writes to arrays and reads from arrays for writing to the database
My question is should the onSensorChanged method be synchronized?
Most importantly, I do not miss any data. Every 10 ms I need to save the current sensor values - no one can be skipped.
So, in my opinion, a synchronized method means that the user interface thread will contain a lock and it will write sensor values to arrays. During this time, the stream of executors cannot read from these arrays due to blocking. Then the lock rises, and the stream of executors is then blocked, read from arrays and written to the database, releases the lock
Perhaps I misunderstand the use of synchronized methods, especially considering that onSensorChanged is event driven, and I'm not sure how this happens in it
But it seems that in such a situation, I could not insert the most recent values every 10 ms. When the user interface thread sets a lock, the worker thread cannot write these values to the database. By the time the stream of artists can be recorded, the values will now have a few ms old and inaccurate
On the other hand, synchronization will mean that I have no situations where the user interface thread changes the values of the array, while the worker thread inserts half of the changed values into the database
So, for this type of situation where I need to insert the most recent / accurate sensor data every 10 ms, should I use the synchronous method?