I have created a metronome android application which writes synthetic sound to an AudioTrack instance. When I ran it it locked up my app completely. I understand that problem and have got round this with creating the instance in its own thread.
i have been reading as much as i can about sending messages between threads, but i can not find any resources detailing how i could go about setting vars and calling methods (eg. start(), stop(), setBpm()) of the metronome instance from the main thread once it has been instantiated.
Im not particularly looking for a straight out fix all answer as i probably wouldnt understand it enough to implement it. if you could point me in the direction of some good reading / examples that would be better.
thanks
Fundamentally you have a class implementing Runnable that is your thread. Keep a reference to that from your main thread and you can call methods in it.
When your main thread creates the Runnable it should pass in a reference to anything the Runnable needs to access - this can include a reference to the main object or any other object if desired.
So long as you properly synchronize the calls the two threads can then communicate with each other by making changes to the objects.
You should check out:
ExecutorService
java.util.concurrent
synchronized
That should give you a good set of tools to get started with.
Related
I am trying to figure out which threads should do what in Android.
The only thing I have found stated in the official documentation is that camera.open() should be put into its own thread.
What about:
camera.startPreview()
camera.stopPreview()
camera.release()
It doesn't state which thread they need. Must they be run on the main thread (ui thread)? Or am I free to choose?
Why am I trying to figure this out? camera.startPreview() when run on the main thread is causing my app to jitter/lag for a short period of time, this heavily affects my application as it is put inside a viewPager and I do not wish to have the camera to always preview (which would cause no lag, but takes up system resources).
Any ideas?
The documentation for Camera states that the class is not thread safe and should not be called from multiple threads at once (I suppose, unless you are performing your own synchronization).
It says that the callbacks will be delivered to the thread that makes the call to open
From the reference (emphasis mine):
This class is not thread-safe, and is meant for use from one event thread. Most long-running operations (preview, focus, photo capture, etc) happen asynchronously and invoke callbacks as necessary. Callbacks will be invoked on the event thread open(int) was called from. This class's methods must never be called from multiple threads at once.
From the open(int) method reference:
Callbacks from other methods are delivered to the event loop of the thread which called open(). If this thread has no event loop, then callbacks are delivered to the main application event loop. If there is no main application event loop, callbacks are not delivered.
Caution: On some devices, this method may take a long time to complete. It is best to call this method from a worker thread (possibly using AsyncTask) to avoid blocking the main application UI thread.
The thread it needs is the one you use to call open(int).
So to answer your question, yes you are relatively free to choose, but you must remain consistent.
I was reading some articles on topic "implement runnable vs extend thread" and I do understand that implementing runnable is prefered because in Java you can't have multiple inheritance. I also read some article that said when you use run() method it just executes the code in current thread, and when you use start() it creates new thread which is I think better, but it depends. But I am still confused about, why you should implement Runnable in class? Why is that needed? Or extending Thread? You can create anonymous thread and start it without implementing runnable or anything.
Sample code of anonymous thread without implementing or extending
new Thread() {
public void run() {
System.out.print("Example");
}
}.start();
EDIT: After some answers and comments, I think what I did not understand was bit more clarified. I actually did not know the reason of implementing Runnable if its run method does not create new Thread. But many of you told me you can use something like this
new Thread(new Runnable())
So finally I want to know - This code up here, does it create a new Thread and executes the code inside the run method ?
Runnable or Callable is the preferred idiom
Pretty much always implement Runnable or Callable you should never in normal cases need to sub-class Thread directly.
If you do need specialized behavior of the Thread class, you either know what you are doing and why you need a different behavior for the Thread class for a good reason, or you are in way over your head.
Executors are the way to go
For most cases you should be using Executors and the plumbing around them instead of rolling your own when dealing with multiple Threads and their interactions and management.
You should never create a new Thread and manage its life-cycle anymore, error prone and hard to manage, lean on the Executors and leverage them.
why you should implement Runnable in class?
The only way to implement any interface is to define a class. Here are docs on Java interfaces.
Why is that needed? Or extending Thread?
You need to do one or the other if you want to use Thread directly. As others have pointed out, you should take a look at the ExecutorService classes which provide thread-pool support and hide the Thread stuff from the user. Here's the tutorial on the subject.
You can create anonymous thread and start it without implementing runnable or anything.
Your code is an anonymous class that extends Thread. As Ishtar provides, here are the docs about anonymous classes in case there is a question. If you looked at the .class files generated by the Java compiler from your code sample you would see something like Main.class and Main$1.class. Java is actually creating a class for you on the fly.
You could also so an anonymous class which implements Runnable:
new Thread(new Runnable() {
public void run() {
System.out.print("Example");
}
}).start();
But whether or not your use an anonymous class is orthogonal to the question of whether implementing Runnable or extending Thread is the better mechanism to define your thread task. For that question, as #MiserableVariable points out, Jon Skeet's answer is still very relevant.
When you deal with your own class hierarchy, you don't want to start from the Thread class in the first place. Thread class is an infrastructure for running your Runnables. And there is more, e.g. Executor, etc. Thread holds its state specific to its API. Runnable is a convenient (and a proper) way of wrapping your processing logic and isolate it from the surrounding it should be executed in.
It depends on your requirements, but in general it is a good idea to seperate What should be done? from Who does it?.
A Thread can execute code, but it has a lifecycle and once it finished you can't start the same Thread instance again.
A Runnable is just some code that can be executed or run(). The lifecycle of the object that implements Runnable is not necessarily bound to a thread's lifecycle and this gives you great benefit:
The same Runnable instance can be run multiple times. If you want to re-run a Runnable just create a Thread, pass the Runnable into the thread's constructor and call start().
Since a Runnable instance can be re-run easily the instance can remember the previous run's state.
The same Runnable instance can be run by multiple threads in parallel.
When you call run() method, it is method invocation on same thread rather than new thread. If you want something happen on separate thread, you either need to extend Thread (or) implement Runnable and call start() on thread object. Java thread life cycle may give you some clarity on difference between calling run() and start()
Quoting from the Oracle documentation on Concurrency.
The first idiom, which employs a Runnable object, is more general,
because the Runnable object can subclass a class other than Thread.
The second idiom is easier to use in simple applications, but is
limited by the fact that your task class must be a descendant of
Thread. This lesson focuses on the first approach, which separates the
Runnable task from the Thread object that executes the task. Not only
is this approach more flexible, but it is applicable to the high-level
thread management APIs covered later.
Note that the first idiom is Runnable and the second is extending from Thread. It looks like flexibility is the main motivator to go for implementing Runnable approach over extending Thread. I highly doubt if they both map to different implementations by the JVM (although I can't confirm it).
Anonymous classes are useful, but not applicable in most scenarios. This is as true for a Thread class, as for any other type of class.
In cases, for instance, that multiple instantiations of a Thread object are needed and that Thread object also has state (e.g., some calculation results), or communicates with other objects (e.g., via a queue), one has to extend the Thread class, or implementing the Runnable interface and then using a Thread constructor to actually start the thread.
The subject has been discussed extensively, so you can check the answers (and the links) posted to an earlier StackOverflow question, or many other similar ones.
I wrote an app on android in which a thread is created through the main activity(UI thread), the new thread saves the activity instance and then calls a method in it while running.
I got an error "Can't create handler inside thread that has not called Looper.prepare()" and found out in this post:
Can't create handler inside thread that has not called Looper.prepare()
and in many more questions that i can't call a method of another thread directly, i should use runOnUIThread or doInBackGround and so on...
my question is WHY?
what's wrong with that design?
thanks in advance :)
You seem a bit confused - the question does not make much sense, so it's quite hard to answer.
Bits and pieces:
creating a thread in UI thread that "saves the activity instance" is wrong in itself: lifecycle of activity is complicated and you should not refer to it by instance.
you cannot "call a method of another thread" (unless you mean the java.lang.Thread object itself, and from the context it seems that you don't), because objects do not belong to any thread. All objects in Java live on heap and can be accessed by any thread.
BUT since each thread is an object, you can have a Map that holds objects indexed by thread instances. This is basically what ThreadLocal is.
Android introduces concept of "Loopers" - you can build one in any thread and call it; if you do, you can say that the thread "has a looper". A thread that has a looper is stuck in a loop, doing any work that handlers pass to it, and - after finishing each task - waiting for another to come by. This is what the main thread does all the time. If you build a handler instance, the handler can be called from any thread, but is connected to the looper of the thread that called the constructor.
Since handlers work by passing work to loopers, they can only be built in threads that have loopers.
I am not sure what you want to achieve, but the bottom line is:
your idea of holding a reference to Activity is wrong - just let it go (and use Loader API or a Service)
you try to build a Handler instance on some custom thread that has no Lopper (probably adding the looper is NOT what you want, instead you want to build the Handler in your main thread)
you imagine objects as being owned by threads - try to get rid of this idea, it skews your way of thinking.
I have a class that extends Thread that downloads files. I want to ensure that only one download is occurring at once, so I have a static reference to the class, and check to see if it is null before creating a new reference. However occasionally I notice that another instance of this class is created, and therefore downloading on a different thread. I'm trying to figure out what could cause this, however, would it be a bad idea in general to mark the run() method of the Thread to synchronized (or the method that calls start()) ? Are there any side effects to be aware of?
you need to ensure only a single instance of your said object get created in lifetime of JVM. for that there is a much famous singleton pattern which ensure this.
Make the constructor private. Give a static factory method to create the instance.
Example:
Downloader{
private static volatile Downloader iDownloader=null;
private Downloader(){
}
public static Downloader createDownloader(){
if(iDownloader==null){
synchronized(Downloader.class){
if(iDownloader==null)
iDownloader=new Downloader();
}
}
return iDownloader;
}
}
if you want limit number of downloads running at any time you should use a semaphore mechanism in this way u can scale number of downloads, you should not need any synchronized run in this way, also in future if u need two downloads run you just increase your semaphore size
Yes you need to synchronize access to the static flag. And it's fine to do that with synchronized methods. However when you're all done you will have implemented a lock. So have a look at the Java Lock class. The method that starts the file transfer needs to grab the lock before starting the download thread. The thread releases it after either the download is complete or has failed. As the docs point out, release must occur with 100% certainty, or all downloads will be blocked.
you can make your thread a pipeline thread by using Looper class from Android Framework and enqueue your download requests by a Handler instance
here is a nice tutorial that might help you
http://mindtherobot.com/blog/159/android-guts-intro-to-loopers-and-handlers/
I have a Java thread that I start so it keeps listening to a socket (considering the a socket read is blocking a thread is needed).
After the Thread receives the data from the socket it needs to call a method from a class.
Now I have two options to do this:
Declare an interface that is passed to the Thread and implemented in a class. When the thread calls the interface method the implementing classes will run it.
Or I can pass the class instance to the Thread as a parameter and then call the class method.
But I wanted to know if the thread blocks while the method is running.
I suppose so but I'm not sure.
I wanted the thread to have a Socket event behavior. What I mean is to only be responsible for reading the data from the socket and fire functions in the main Class, the one that called the Thread.
Yes, the thread will block while executing the method, so it can not read from the socket at the same time. No information will be lost, the transfer only takes longer and you can get a socket timeout if the computation takes too long.
If your method takes much time to run, you should execute it in another worker thread. I recommend to use an Executor for that.
You have various options :
Make your class a child class of Thread (easier code but you'll merge functionnal part - your main code - with a technical aspect (extending the Thread))
Make your class implements the Runnable interface and start a new thread with that Runnable (i often do like that). So your main code still remains in a overriden run method, but the inheritance tree is up to you (your main class can extend one of your other class)
Keep separated your main code / the thread with two classes (one for your main code, one for the thread), linking the two at your will (remember that if you make an inner thread inside another class, the inner thread can use any final properties, for example).
As stated in other answers, anything happening in your run() method is of course blocking the execution.
As a sidenote, if you're going to deal with threads and sockets, i strongly suggest you to have a look at NIO frameworks like Netty that are just there for this kind of behavior : event driven client/server application through NewIO sockets.
As another sidenote, i often use this pattern :
start an acquisition thread that will catch the event ;
push them in a linkedblockingqueue (queue.offer()) ;
have another thread that shares the same linkedblockingqueue (with queue.take()) : this operation is blocking, the threads will be blocked as long as the queue is empty ;
This is a very simple way to have one thread as "producer", and one thread as "consumer". You can even have various consumers awaiting on the same queue.
But I wanted to know if the thread blocks while the method is running
Yes it does block.
If inside run you call a method to process something it doesn't matter if that is an interface etc as you ask it only matters what does the method actually do
In your case you have only 1 option.
Make sure that you return the control back to your socket listening thread asap.
This can happen by designing/mandating the processing class to handle the processing in a different thread.
Actually your problem is not something new. In event based designs there is the requirement to process the event as fast as possible so as to not block the event queue based flow.
And this is how I would recommend you to design arround. Not use any interface to interact with the listening thread but register an event listener(s).
When an event occurs i.e. your listening thread reads data, it will pass the data as event to your listener(s) at which point of course it will block.
Then you should start a new thread to do the processing and the listening thread can continue with its work