aeroxr1
aeroxr1

Reputation: 1074

Android Concurrent : UI thread edit a variable and other thread read the same variable

I have one doubt relative concurrent between UI thread and other thread.

Ui main thread update the value of different variable : - float - long - boolean

And I have another thread that reads the same variable and does some logic operation (without edit its values) with that and send local broadcast message with the result of this operation.

Are there concurrency problem and I have to use : synchronized method and atomic variable or it doesn't matter ?

I reflect on this problem, because there isn't atomic variable for float primitive , and because I'm scared to block Ui thread with the wrong code..

EDIT: Other question

Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).

from : https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html

Then the int,double primitive type are atomic right ? The problem is on long and double.

For example :

class test
{

    int c=0;
    long p=0;

    new Thread1( new Runnable(){

     public void run(){
       a=a+c;
       p=p+c;
     }
    }
    ).start();

   new Thread2( new Runnable(){

     public void run(){
       c=function();
       p=functionx();
     }
    }
    ).start();

    ....
}

I have to use volatile int for the visibility problems between thread or it doensn't matter ? and for the long variable should I use the atomicLong because the operation on the long primitive aren't atomic ?

p.s : I don't really understand the variable visibility problem between threads

Upvotes: 0

Views: 819

Answers (1)

edharned
edharned

Reputation: 1904

Take a look at another answer I gave on SO What you probably need is to make the variable volatile. UI thread, not UI thread, a thread is a thread. The importance of modifying a variable on the UI thread is so that variable will be displayed. What you are doing is sending that modified value somewhere else.

From what I understand of your question: just make the variable volatile and you should be fine.

Upvotes: 1

Related Questions