views:

415

answers:

2

I'm programming on Android, but I guess this is a general Java 101 question...

I want myMethod() to run every X ms without blocking the UI - it should be possible to start and stop this thread. The value of X milliseconds will change whilst it's being run. myMethod() needs read access to an array which is manipulated by the UI.

How can I do this? As the interval changes I can't use schedule(); so is this a valid case for sleep(int X)? If I do start a new thread (runnable or extending Thread) in a new class, how can I read the UI class's array? (does something like parent.getarray() exist?). What's the best way to tackle this?

+2  A: 

You could create a java.util.Timer object keeping a TimerTask object around. That way you could simply schedule the Timer each time for the desired X to act on the TimerTask

http://developer.android.com/reference/java/util/Timer.html http://developer.android.com/reference/java/util/TimerTask.html

metismo
+3  A: 

ScheduledThreadPoolExecutor class gives you scheduling functionality. It has some advantages over java.util.Timer

I don't know Android, but it seems that ScheduledThreadPoolExecutor is available on Android as well.

Using STPE is simple: you create your Runnable or Callable instance, and pass it to your executor via schedule method together with scheduling information (how often it is called, what is beginning delay).

To access array from your UI thread, you need to use some kind of synchronization. Take a look at AtomicReferenceArray, AtomicLongArray or AtomicIntegerArray if they can help you (they give you atomic access to array elements without any other synchronization, although you better make your array variables final). Other option is to put all reads and writes to array into synchronized blocks. Another possibility is to use CopyOnWriteArrayList. If you need to also update UI from your background task, you need to wrap your updating code into another Runnable and pass it to UI thread. Best option really depends on what exactly you're doing.

Peter Štibraný
+1. Obligatory *Effective Java* reference: http://books.google.fi/books?id=ka2VUBqHiWkC `STPE` is much more flexible.
Jonik
Yup. I have summarized differences between the two at http://stackoverflow.com/questions/409932/java-timer-vs-executorservice/409993#409993 (from different source, JCiP).
Peter Štibraný