Why cant a thread that is not the UI thread access the view?
Asked Answered
A

3

2

I know that no thread can access the current view unless it is the UI Thread. I am wondering why? Why does it matter which thread is changing the view? Is it a security reason? This is the work around I use:

        public void doLayout()
        {
            Runnable run = new Runnable()
            {
                public void run()
                {
                    ViewerActivity.setContentView(R.layout.main);
                }
            };

            handler.post(run);
        }

        private Handler handler;'

It is kind of a pain to do that everytime i want to change the layout. Is there a different work around? I know about async task and i never found a good way to use it, is it better than what i'm doing? All relevent answers are appriciated!

Amimia answered 9/10, 2011 at 1:34 Comment(3)
You should read more about locking/synchronization in Java (i.e. when to use "synchronized") -- once you understand that, it will be obvious why you have to jump through hoops in order to interact with the UI thread from a separate thread.Hysterectomy
The reason for the separation is to avoid deadlocks. Assume for instance that you were allowed to freely modify the view from any thread. Let's pretend you were making a DB call. So you get a handler to a view component then query the database, but the database locks and subsequently locks the current thread. Now the UI thread will also be locked since you were in the middle of modifying the view and it has to wait for it to be freed before it can continue safely. This would create really bad programs that would end up locking up a lot more than they currently do.Jotter
Most UIs, regardless of platforms and language can only access the UI in the main UI thread, and the reasoning is usually that making a thread safe UI is very hard and not worth the effort, and it would incur quite severe speed penalties that's undesired as a graphical UI environment needs to be fast and responsive.Eisenberg
F
17

Yes your right: You can't modify views on another thread for the sake of security (that's why it's called UI thread). It prevents you from leaving the UI data in an inconsistent state which might crash your application and would be really hard to debug. So the android API simply forbids that (and that's a good idea). That's a common UI pattern which you'll find in the most APIs.

You can update any view with post() or runOnUiThread():

anyView.post(new Runnable() {
    public void run() {
        // do update here
    }
});

Why this pattern?
Synchronization is not for free. It impacts the performance. So it's easier to keep modifications to UI on the same thread.

If I could modify data from different threads what could happen?
For example: Thread A is changing the color of a view and thread B is reading the color at the same tim. Since multi-threading doesn't guarantee which instruction is executed first you might get unexpected results. The color is black (0|0|0) before, thread A wants to set white (255|255|255) and start with setting the red component to 255, thread B starts to read and gets the whole color before thread A had a chance to finish and got the color red (255|0|0) instead black.

This is a simple example which would impact a visual effect but if that happens for some really important data your application will crash horribly and such an error is so nasty and hard to debug. There's a lot to learn about multi-threading and maybe this java tutorial is a good starting point...

Francophile answered 9/10, 2011 at 1:45 Comment(0)
W
1

Android application uses Single Thread Model and this thread is responsible to dispatch various events to the UI elements. This single thread model has two rules :

  1. Do not block the UI thread
  2. Do not access the Android UI toolkit from outside the UI thread

If you create a thread that uses View outside the UI thread then it violates the second rules.

Wheaton answered 9/10, 2011 at 2:12 Comment(0)
S
1

Security isn't the only UI thread is the only thread that can access the Views. The main reason is that the code behind the views probably isn't thread safe. This means that there are no guarantees that data won't get corrupted if you have multiple threads reading and writing to common variables.

Check out this great wikipedia article about thread safety.

Sutter answered 9/10, 2011 at 2:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.