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?
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.
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
Related
and excuse the lack of knowledge on multithreaded apps, but I am new to the field.
Is there a pattern or common used methodology for monitoring the 'job completion' or 'job status' of worker threads from a monitor (a class that acts as a monitor)?
What I have currently done is create a list of workers and create one thread for each worker. After all threads have started i am looping over the worker list and 'checking their status' by making a call to a method.
At that time I couldn't come up with a different solution, but being new to the field, I don't know if this is the way to go, or if there are other solutions or patterns that I should study.
Depending on what you want, there are many ways that you can do this.
If you just want to wait until all the threads finish (i.e. all you care about is having everything finish before moving on), you can use Thread.join():
try {
for (Thread t: threadsIWaitOn)
t.join();
} catch (InterruptedException iex) {
/* ... handle error ...
}
If you want a more fine-grained control over the thread status and want to be able, at any time, to know what threads are doing, you can use the Thread.getState() function. This returns a Thread.State object that describes whether the thread is running, blocked, new, etc., and the Javadoc specifically says that it's designed for monitoring the state of a thread rather than trying to synchronize on it. This might be want you want to do.
If you want even more information than that - say, how to get a progress indicator for each thread that counts up from 0 to 100 as the thread progresses - then another option might be to create a Map from Threads to AtomicIntegers associating each thread with a counter, then pass the AtomicInteger into the constructor of each thread. That way, each thread can continuously increment the counters, and you can have another thread that continuously polls the progress.
In short, you have a lot of options based on what it is that you're trying to accomplish. Hopefully something in here helps out!
Use a ThreadPool and Executor, then you get a Future<> and you can poll for their completion and some more nice stuff, too. I can appreciate this book for you: Java Concurrency in Practice
Try to use any kind of synchronization. For example, wait on some kind of monitor/semaphore until job is done / whatever you need.
My extended SwingWorker class performs a potentially reoccurring background task which requires GUI originating input variables.
I see 2 coding options:
To start a new instance of the class each time I use it and pass
the variables to the constructor. I presume I should make sure there
are not to many instances. If so how? multiton or some other method?
Update the variables and call execute again? If so how do I make
sure i'm not interrupting?
Is one of these options the way to go or is there a better way?
SwingWorker is non-entrant, meaning you can not execute it again, much in the same way Threads are.
From the JavaDocs
SwingWorker is only designed to be executed once. Executing a
SwingWorker more than once will not result in invoking the
doInBackground method twice.
Plase use option 1.
Immutable objects are normally easier to work with. For example, you prevent the problem that the variables are updated while the worker is still working, and you have to think less about memory visibility.
Object instantiation is quite cheap in Java, so this won't be a performance problem and you can create a new instance every time to need one.
In my Java application with a Swing GUI, I would like to achieve the following.
There is a non-GUI thread running, performing some work. At one point, this thread needs input from the user before it can continue. Then, I would like to make some changes to the GUI, await a specific GUI action (like the user pressing the OK button), get the entered data from the GUI to the non-GUI thread, and let it continue with the computation.
Looking around, I have found a lot of information about how to initiate the execution of a (long running) task from the Swing GUI thread on another thread, but nothing on my problem.
SwingUtilites.invokeAndWait sounds like it does the job, but first, it takes a Runnable argument instead of a Callable, so there is no straightforward way to return a result, and second, it does not solve the problem of waiting for a certain GUI event.
I realize I could make up my own solution using e.g. a CountDownLatch, but to me, the problem seems frequent enough for there to be a standard solution.
So, my questions are: Is this really a frequent problem, and if yes, is there a solution in the standard library / libraries? If there is no standard solution, how would you solve it? If this problem doesn't occur often, why not?
Kicking off the GUI changes is easy, so I assume you're only asking about getting data back to the worker thread.
First, create a Blocking Queue. Have the worker thread call take() on the queue, and it will block. In GUI space, once the user enters valid input, put it on the queue with offer() and the worker thread will receive the data and can continue.
I think, you can use ExecutorService where you can also track progress of your task through Future interface.
java.awt.EventQueue.invokeLater works nicely for running code on the AWT EDT. Propbably best to copy mutable data or better use immutable data. Locks are possible, but a bit dicey.
If you other thread is an event dispatch loop, you could implement something like invokeLater for your thread (but don't make it static!). Probably use it behind some interface that makes sense to the behaviour of the thread - so it's real operations rather than run which is specified as doing anything it pleases. If your thread is going to block, then a BlockQueue is fine, but don't block from the AWT EDT.
java.awt.EventQueue.invokeAndWait is like using a lock. Probably you are going to use another lock. Or perhaps a lock like invokeAndWait on you own thread. If you don't, AWT uses a lock anyway. So, uncontrolled nested locks, that probably means deadlock. Don't use invokeAndWait!
final bool result = doSomething();
SwingUtilities.invokeLater( new Runnable(){
//Runnable method implementation.
//use result in your method like local var.
});
Make sure that your shared data is synchronized use lock objects.
If you need to pass arguments to Runnable just make your local variables final,
and use them in run method.
I am not understanding this concept in any manner.
public class SomeName {
public static void main(String args[]) {
}
}
This is my class SomeName. Now what is thread here.
Do we call the class as a thread.
Do we call this class as thread when some other object is trying to access its method or members?
Do we call this class as thread when some other object is trying to access this object?
What does it mean when we call something in java as thread-safe ?
Being thread-safe means avoiding several problems. The most common and probably the worst is called threadlock. The old analogy is the story of the dining philosophers. They are very polite and will never reach out their chopsticks to take food when someone else is doing the same. If they all reach out at the same time, then they all stop at the same time, and wait...and nothing ever happens, because they're all too polite to go first.
As someone else pointed out, if your app never creates additional threads, but merely runs from a main method, then there is only one thread, or one "dining philosopher," so threadlock can't occur. When you have multiple threads, the simplest way to avoid threadlock is to use a "monitor", which is just an object that's set aside. In effect, your methods have to obtain a "lock" on this monitor before accessing threads, so there are no collisions. However, you can still have threadlock, because there might be two objects trying to access two different threads, each with its own monitor. Object A has to wait for Object B to release its lock on monitor object 1; Object B has to wait for Object A to release its lock on monitor object 2. So now you're back to threadlock.
In short, thread safety is not terribly difficult to understand, but it does take time, practice and experience. The first time you write a multi-threaded app, you will run into threadlock. Then you will learn, and it soon becomes pretty intuitive. The biggest caveat is that you need to keep the multi-threaded parts of an app as simple as possible. If you have lots of threads, with lots of monitors and locks, it becomes exponentially more difficult to ensure that your dining philosophers never freeze.
The Java tutorial goes over threading extremely well; it was the only resource I ever needed.
You might want to think of thread as CPU executing the code that you wrote.
What is thread?
A thread is a single sequential flow of control within a program.
From Java concurrency in practice:
Thread-safe classes encapsulate any needed synchronization so that
clients need not provide their own.
At any time you have "execution points" where the JVM is running your code stepping through methods and doing what your program tells it to do.
For simple programs you only have one. For more complex programs you can have several, usually invoked with a new Thread().run or an Executor.
"Thread-safe" refers to that your code is written in such a way that one execution point cannot change what another execution point sees. This is usually very desirable as these changes can be very hard to debug, but as you only have one, there is not another so this does not apply.
Threads is an advanced subject which you will come back to later, but for now just think that if you do not do anything special with Threads or Swing this will not apply to you. It will later, but not now.
Well, in your specific example, when your program runs, it has just 1 thread.
The main thread.
A class is thread safe when an object of that class can be accessed in parallel from multiple threads (and hence from multiple CPUs) without any of the guarantees that it would provide in a single threaded way to be broken.
You should read first about what exactly threads are, for instance on Wikipedia, which might make it then easier to understand the relation between classes and threads and the notion of threadsafety.
Every piece of code in Java is executed on some thread. By default, there is a "main" thread that calls your main method. All code in your program executes on the main thread unless you create another thread and start it. Threads start when you explicitly call the Thread.start() method; they can also start implicitly when you call an API that indirectly calls Thread.start(). (API calls that start a thread are generally documented to do so.) When Thread.start() is called, it creates a new thread of execution and calls the Thread object's run() method. The thread exits when its run() method returns.
There are other ways to affect threads, but that's the basics. You can read more details in the Java concurrency tutorial.
I have a program that builds the GUI in the constructor. I need a Thread separate from the EDT to run immediately after the object in question is constructed. Could anyone point me in the right direction?
I need a Thread separate from the EDT
Threads are separate from the EDT so all you do is create a Runnable and then start it.
You only have to worry if the Thread updates any GUI components. If this is the case then you may want to use a SwingWorker. Read the section from the Swing tutorial on Concurrency for more information.
What you want to use is a SwingWorker<T,V>. In the doInBackground method, open the connection and start fetching data. When you have enough data to update the gui, call the publish method. Implement the process method to update the gui with the new data from publish, and finally, implement the done method to notify the user when you're finished fetching data.
The Swing Worker is a generic, so when you construct it you need to provide two types: T and V. V is the type for the data passed between publish and process methods and T is the type returned by doInBackground and passed to done.
build your GUI an open a new window inside a new Runnable invoked called by: SwingUtilities.invokeLater
you have two choises
1) wrap Thread into Runnable as demonstrated here
2) I am not very satisfy with plain SwingExecutor, then I use for that Executor and SwingWorker, monitored by PropertyChangeListener, example here,
please carrefully with number of threads started by Executor. Executor doesn't care if SwingWorker ends or not and there still exists Bug where is pretty possible to overload maximum (somewhere in API) simultaneous jobs live by Executor in same time.
by this reason is there possible implements PropertyChangeListener