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/
Related
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.
I have a class "A" with method "calculate()". Class A is of type singleton(Scope=Singleton).
public class A{
public void calculate(){
//perform some calculation and update DB
}
}
Now, I have a program that creates 20 thread. All threads need to access the method "calculate()".
I have multicore system. So I want the parallel processing of the threads.
In the above scenario, can i get performance? Can all threads access the method calculate at same instance of time?
Or, Since the class A is singleton so, the threads needs to be blocked waiting.
I have found similar questions in the web/Stackoverflow. But I cannot get clear answer.
Would you please help me?
Statements like "singletons need synchronization" or "singletons don't need synchronization" are overly simplistic, I'm afraid. No conclusions can be drawn only from the fact that you're dealing with the singleton pattern.
What really matters for purposes of multithreading is what is shared. If there are data that are shared by all threads performing the calculation, then you will probably need to synchronize that access. If there are critical sections of code than cannot run simultaneously between threads, then you will need to synchronize that.
The good news is that often times it will not be necessary to synchronize everything in the entire calculation. You might gain significant performance improvements from your multi-core system despite needing to synchronize part of the operation.
The bad news is that these things are very complex. Sorry. One possible reference:
http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601/ref=sr_1_1?ie=UTF8&qid=1370838949&sr=8-1&keywords=java+concurrency+in+practice
That's the fundamental concept of Singleton. Only one instance of the class would be present in the system (JVM). Now, it depends on the implementation of calculate(). Is it a stateless utility method? If yes, you might not want to make it synchronized. In that case, multiple threads will be able to access it at the same instance of time. If calculate() is NOT stateless, i.e. it uses instance variables (and those instance variables will be used by multiple threads), then be careful; You have to make calculate() thread safe. You have to synchronize the method. At least you have to use a synchronize block inside the method. But, once you do so, only one thread will be able to access it (the synchronized block or the synchronized block inside the method) at any point of time.
public void calculate() {
//Some code goes here which does not need require thread safety.
synchronized(someObj) {
//Some code goes here which requires thread safety.
}
//Some code goes here which does not need require thread safety.
}
If you want to use parallel processing (if that's the primary goal), then singleton is not the design pattern that you should use.
I have found similar questions in the web/Stackoverflow. But I cannot get clear answer.
There is a good reason for that!!
It is not possible to say whether a method on a singleton does, or does not, need to be synchronized by virtue of being singleton.
Synchronization and the need for synchronization is all about state that may be shared by different threads.
If different threads share state (even serially), then synchronization is required.
If not then no synchronization is required.
The only clues that you have provided us that would help us give you a yes / no answer are this enigmatic comment:
// perform some calculation and update DB
... and the fact that the calculate() method takes no arguments.
If we infer that the calculate() method gets its input from the state of the singleton itself, then at least the part of the method (or the methods it calls) must synchronize while retrieving that state. However, that doesn't mean that the entire method call must be synchronized. The proportion of its time that the calculate method needs to hold a lock on the shared data will determine how much parallelism you can actually get ...
The updating of the database will also require some kind of synchronization. However, this should be taken care of by the JDBC connection object and the objects you get from it ... provided that you obey the rules and don't try to share a connection between multiple threads. (The database update will also present a concurrency bottleneck ... assuming that the updates apply to the same database table or tables.)
It depends on how you implement Singleton. If you use Synchronized keyword then they will wait else not.
Use Singleton with eager initialization.
Something like this:
public final class Universe {
public static Universe getInstance() {
return fINSTANCE;
}
// PRIVATE //
/**
* Single instance created upon class loading.
*/
private static final Universe fINSTANCE = new Universe();
/**
* Private constructor prevents construction outside this class.
*/
private Universe() {
//..elided
}
}
Above will perform very well in multithreaded environment. or else you can go for enum implementation of Singleton.
Check this link for various singleton implementation: http://javarevisited.blogspot.in/2012/07/why-enum-singleton-are-better-in-java.html
Multiple threads can invoke calculate() at the same time.
Those invocations won't be queued (executed serially) within that JVM unless you perform some type of concurrency control (making the method synchronized is one option).
The fact that your object is a singleton may or may not affect performance, depending on how that object's attributes (if any) are used within calculate().
Also bear in mind that since you are "updating DB", table or row level locks may also limit concurrency.
If you are worried about performance, the best bet is to test it.
I have an application where i need to call 3 methods in 3 seperate threads and kill them afterwards. According to the Javadoc i noticed that thread stop() and even destroy() has been deprecated. its like I start one thread after the other and then kill similarly one after the other. Is there a particular way to kill the threads because I cant use the deprecated methods
Any help much appreciated.
Thanks again
You don't kill threads. You call Thread.interrupt(), and then react to the interrupted status or InterruptedException within the thread that's being interrupted. Or, you use a volatile flag. See the official documentation for background and more info.
Even better, use a thread pool / executor instead of raw threads, as suggested in comments.
Terminating a rogue thread in a way that works every time everywhere is pretty much impossible.
If you can control the source code of the running threads, you must add a method with which you can stop the thread when you need to. Basically this method changes a boolean variable and the thread checks that value periodically to see whether or not it can continue.
public class MyTask implements Runnable {
// Set this to true when thread must stop.
private boolean mStopRequested = false;
public void run() {
while (mStopRequested == false) {
// ...
}
}
}
If you call a 3rd party libraries that do not provide such a method, then you are out of luck and have to resort to ugly kludges. Once I had to kill a long running 3rd party library call by deleting a file that was accessed by the library (it threw a FileNotFoundException and exited). And that only worked on Unix systems.
Your mileage will vary.
Use join method until the receiver finishes its execution and dies or the specified timeout expires, whatever happens first.
thread1.join(1);
thread2.join(2);
thread3.join(3);
You must handle the exception.
I am working on an application, that processes incoming messages. I am not proficient in java multithreading and I am asking your help, folks. Is there anything wrong with the following app structure.
There is main application class with stopRequested boolean field. And there is internal runnable class that listens for incoming messages and process them. Also there is another thread that sets stopRequested to true.
Is this approach working and reliable, or I am wrong?
Below there is a part of my code:
class ApplicationClass {
// we set this var in another thread
// when it is necessary to stop
private stopRequested = false;
public ApplicationClass() {
// starting message processing thread
(new Thread(new MessageProcessing())).start();
}
private class MessageProcessing implements Runnable {
public void run() {
while (!stopRequested) {
if (getNewMessagesCount() > 0) {
processNewMessages();
}
}
}
}
}
Thank you.
There are a few things to think about.
As sbridges noted stopRequested needs to be volatile to resolve visibility problems (a thread on another core may not see the change otherwise).
If getNewMessagesCount() doesn't block then your while loop will spin and consume the core; this will give you the lowest latency but ties up the entire core.
The code you've listed appears to be a simple processing queue; you're likely going to be better off going with an ArrayBlockingQueue.
It's dangerous to start a new thread from a constructor. The thing to worry about is what happens if getMessageCount() and processNewMessages() are invoked before ApplicationClass is finished being created. Since the instance of ApplicationClass could be in an incomplete state you could find a rather nasty bug. (For the same reason you never want to have your code subscribe as a listener to events from a constructor, by the way.) Check out Effective Java for more background on this topic.
Your while loop should check if the current thread has been interrupted so that it places nice; it should be while (!stopRequested && !Thread.currentThread().isInterrupted())
Writing correct concurrent programs is hard. I highly recommend reading Java Concurrency in Practice; it will save you a lot of pain.
It is hard to comment on performance without knowing more details, you will probably want to benchmark.
The code looks correct, except you will want to make stopRequested volatile. If it is not volatile, the processing thread may not see it being set to false. Rather than use methods like getNewMessageCount(), you might want to use a LinkedBlockingQueue, and use the poll() method on that.
I actually have two questions about Java RMI and thread synchronization:
1) If I implement my RMI remote methods as synchronized, are they guaranteed to be mutually exclusive? I need to make sure that no two of my RMI methods (methods offered to clients) execute at the same time.
2) I have a method that the server executes periodically. It is used to do cleanups. I have to make sure that this particular method does not execute when there is any RMI method being run/used by remote clients. Also, when that method is running, RMI calls shouldn't be possible. I.e. Clients must wait. Any idea how I can do that? I have read about Locks, but I do not know how to use them in this scenario.
I have considered implementing RMI methods as static and including that cleanup method inside the RMI interface, but it does not seem to be an elegant way of solving the problem.
I have also written the cleanup method inside the RMI interface as synchronized. When I ran it for testing, there did not seem to be collisions between methods, but I cannot be sure.
Thank you for your time and answers.
1) If I implement my RMI remote
methods as synchronized, are they
guaranteed to be mutually exclusive? I
need to make sure that no two of my
RMI methods (methods offered to
clients) execute at the same time.
RMI does not provide such guarantee on its own (unlike EJB) and two calls on the same remote object may be executed concurrently unless you implement some synchronization. Your approach is correct, and synchronizing all methods will indeed ensure that no two of them run at the same time on the same object. Note: The keyword synchronized alone is equivalent to synchronized( this ).
2) I have a method that the server
executes periodically. It is used to
do cleanups. I have to make sure that
this particular method does not
execute when there is any RMI method
being run/used by remote clients.
If the cleanup job is in another class, you will need to define a lock that you will share between the remote object and the cleanup job. In the remote object, define an instance variable that you will use as a lock.
protected Object lock = new Object();
By convention, people use an Object for this purpose. Then you need to grab the lock in your periodic job with synchronized( remoteObj.lock ) { ... }, assuming it's in the same package.
The other methods in the remote object will need to be synchronized the same way (synchronized alone is not enough), so that remote method calls and periodic job are both exclusive.
I have considered implementing RMI
methods as static and including that
cleanup method inside the RMI
interface, but it does not seem to be
an elegant way of solving the problem.
I have also written the cleanup method
inside the RMI interface as
synchronized. When I ran it for
testing, there did not seem to be
collisions between methods, but I
cannot be sure.
If I understand well, you would like to have the cleanup logic be a static method? A static method with synchronized alone grabs a lock on the class. A "regular" method with synchronized grabs a lock on the object instance. These are not the same implicit locks!
But if you have only one remote object instantiated, you can make the lock static (That's the same as locking on the class, but is a bit cleaner). The cleanup code can then be static as well and be in the same class as the remote object or not.
Skeleton:
public class MyRemoteClass {
public static Object lock = new Object();
public void doStuff()
{
synchronized( lock ) { ... }
}
}
public class Cleanup {
public static void doIt()
{
synchronized( MyRemoteClass.lock ) { ... }
}
}
For each call from a RMI client the RMI server will execute the call in a new thread. You only need to synchronize access to shared objects.
Another thread or timer will not stop your server from accepting calls from the client side. This needs synchronization, the best practice depends on how long the cleanup job runs can it be interrupted, or would it be possible to put the requests in a queue etc.
The easiest way would be to let the RMI methods wait for the lock as already described by ewernli.
EDIT: According to your comment, a skeleton that demonstrates how to achieve this kind of basic synchronization. Since everything is now mutually exclusive, you can't expect high performance with multiple clients involved. Anyway this would cover your requirements. (I hope). If your project grows you should read the Concurrency Tutorial
Object mutex = new Object();
int rmiMethod1() {
synchronized (mutex) {
doWhatNeeded1();
}
}
int rmiMethod2() {
synchronized (mutex) {
doWhatNeeded2();
}
}
// in your cleanup thread
void run() {
synchronized (mutex) {
cleanUp();
}
}
To clarify all this confusion:
If you synchronize your remote method implementations only one client can be executing at a time.
If you synchronize your cleaner task on the remote object it joins (1).
You can't define remote methods as static.
You must keep in mind that RMI creates the illusion of a "remote object", but in reality there are no less than three objects: the local stub, the remote skeleton and the actual remote object. As a design trade-off this illusion is not complete and is locking only the local stub. There is no synchronization across the network. Search the internet for RMI+stub+synchronized and you will find plenty of explanations, like for instance this one:
Java RMI and synchronized methods
So you need to implement some kind of non-RMI, purely server-side synchronization yourself. Then you can invoke this pure server-side locks from your remote methods; but you need the additional level of indirection.
To test your code the easiest is to pause your threads under a good debugger like Eclipse. Eclipse will clearly show you which paused thread is holding which lock blocking which other thread(s).