Note that there are some explanatory texts on larger screens.

plurals
  1. POSensorEventListener and Timer-thread using shared Vector
    primarykey
    data
    text
    <p>What is the best way to handle competing threads that are reading data from a vector?</p> <p>I'm trying to write an android app where I'm trying to read sensor data periodically and write it to a file and then upload the file to a remote server. </p> <p>What I do as the first step, I register the SensorEventListener for each sensor and then, whenever sensor values change, I push new values to a <code>Vector()</code>. Here <code>data</code> is a vector of user defined object.</p> <pre><code>@Override // when sensor value is changed, this method will be called. public void onSensorChanged(SensorEvent event) { synchronized (this){ Datapoint dp=new Datapoint(event.sensor.getType(),event.values); data.add(dp); } } </code></pre> <p>As the next step I use a <code>Timer</code> object to periodically read off data from the <code>data</code> vector and send it to a remote server. </p> <pre><code>class calculateSensorData extends TimerTask { public synchronized void run() { for (Datapoint item : data) { //use data } data.clear(); } } </code></pre> <p>The main problem is when I try to access the data vector inside the <code>TimerTask</code> I get <code>java.util.ConcurrentModficiationException</code>. </p> <p>I think this is because both the sensor listener thread and timer thread are trying to update/modify the shared Vector at the same time. </p> <p>I got around the problem by un-registering the listeners at the start of the <code>Timer</code> task. But that not a good solution. </p> <p>Any other way to accomplish this without un-registering and re-registering all sensor listeners each time the <code>Timer</code> fires.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload