0

I'm having a bit of trouble with concurrency. The situation is as follows:

I have a method which adjusts brightness like so (it is executed in the UI thread):

public void adjustBrightness(final float brightness) {
    window_object.setBrightness(brightness); 
    window_object2.setBrightness(brightness);
}

The setBrightness method called on those objects is the second block of code in this question: Clean way to implement gradual fading of brightness in Android?

As you can see, that block of code executes within another thread. This is problematic, because it means that setBrightness returns as soon as the thread is started, causing window_object2 to adjust its brightness whilst window_object is still adjusting. I do not want them to execute concurrently!

How can I enforce sequential execution of these methods such that they do not interlace? Keep in mind I need methods which are considered 'safe', so I don't get obscure concurrency bugs.

Thanks.

Community
  • 1
  • 1
Glitch
  • 2,785
  • 1
  • 27
  • 50

1 Answers1

1

Simple: delete the second line.

You only have one screen. The code you linked to affects the brightness for the whole screen. Hence, you only need to run that code once.

That code you linked to is rather inefficient, BTW -- use postDelayed() and get rid of the background thread.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Indeed, I only have one screen, but I'm actually doing work with overlays which darken the screen. My real code isn't as simplified as the block I linked, it can adjust both brightness and alpha values of a window. So what this code is actually doing is gradually adjusting the alpha of one window, and then the screen brightness of the other. I just don't want this to happen concurrently. With regard to postDelayed(), could you detail the usage you have in mind? A loop which posts the Runnable via the Handler with a delay instead of the TimerTask? – Glitch Sep 10 '11 at 13:09
  • @Glitch: "and then the screen brightness of the other" -- you don't change the screen brightness of a window; you change the screen brightness of the screen. "I just don't want this to happen concurrently" -- then don't use multiple threads. "With regard to postDelayed(), could you detail the usage you have in mind?" -- call `postDelayed()` with a `Runnable` that does work, then schedules itself for the next delay. – CommonsWare Sep 10 '11 at 14:08
  • Thanks for the postDelayed() tip! I'd still like to know how to make the above code threadsafe, for future reference. – Glitch Sep 10 '11 at 15:52