ScheduledExecutorService and Threads in Java - java

How does scheduler work here ? Does it create a new thread in the background and execute Run method in the main thread like a callback. ? . When run method is getting executedl, is it belong to the main thread?
classA implements Runnable
{
public void Run()
{
System.out.println(Thread.currentTread().getName());
}
public static void main(String args[])
{
Thread.currentThread().setName("Main");
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(this, 250, 250, TimeUnit.MILLISECONDS);
}
}
Thanks.

How does a SingleThreadScheduledExecutor work ?
It creates a thread pool that will at most contain one thread. This makes sure that only one task at a time (that is scheduled on this executor) will run.
Tasks run in the executor's single thread, not on the thread that has submitted them.
Can you make it so that the method runs on the "main thread" ?*
Well you can "make" anything, right ? But not with an ExecutorService, it is designed to work with its own thread.
How so then ?
Basically, either you're in an environment that provides everything to you (UI applications in Swing do for example), so check if this is your case (Swing has the Event Dispatch Thread). Either you nedd some work. So I'd first suggest you make sure you really NEED to work in the main thread before going on and doing this work.
What does this work involve ?
Without any special work, your main thread execute codes that is an ininteruptible flow of satements. They are written once, nobody can "inject" code into your main thread (well, unless you get really messy with your memory, which you can, but that is not something one usually do).
So your main thread is busy doing task A, then B, then C, then D in order, as fast as it can (or is allowed to). You can not inject "task E" in the middle of this flow.
Metaphorically, this would be the equivalent of chossing a random line in your code, and add statements of another method right there : crash guaranteed (what is the context, what is the stack, what variables exist at this particular line, and with which value : unpredictible). This can not happen.
And so, even if task A is "create a task to execute in 4 seconds", what will happen is : in another thread you get notified in 4 seconds that the timer expired, and this other thread will get to decide what to do, because the main thread is in the middle of doing "task B", and there is nothing else it can do.
So basically... it can't be done ?
Oh yes, it can. But you have to make "task A" (or B, or C), special for it to work. You have to design your main thread to periodically "wait" for events that come from outside.
And there is not a great many deal of ways to do that : periodically do something. You have to make your main thread performe an "loop". This pattern is called a run loop. Many many UI frameworks run this way.
What happens is that :
you create a Queue, and make it globally accessible (Singleton pattern, for example) to your program. The goal of this queue will be to receive all the work units that the main thread is supposed to execute.
Upon start, you make your main thread spawn a secondary thread that will be responsible to continue the initialization process and life of your application after step 3
you make your main thread enter an infinite loop waiting for new events from the queue
With your "secondary" thread, you can then do anything you like, including setting your first timer. When the timer fires, it should send the work to be performed (say a Runnable instance ?) to the queue. The main thread will pick up that a run the runnable inline.
Is that efficient ? Waiting for events ?
Yes it can be. If you use well purposed objects (ConcurrentQueue ?) that are designed for concurrency, you do not actually perform work and waste resources while waiting. What happens under the hood is that threads are "signaled" by the operating system that new units are available. So it's not an infinite loop where you say "is there something to do ? If yes > do it, if no > wait three seconds". It's "Signal me when there's something to do".
I do not know of any JAR / lib or tool or best practice to actually implement this. Most of the times, either the environment provides this (Swing's ìnvokeLater), either I did not need this kind of things. So I know how this theoretically works, but I guess this is surprisingly difficult to actually implement right.
Wikipedia's entry for this pattern : http://en.wikipedia.org/wiki/Event_loop.
In game programming, one often have a "game loop" that is an equivalent pattern

Related

RunLater on current thread or give a task to current thread to run later

I want to achieve what Platform.runLater() does but on the current thread and the program isn't related to JavaFX, it's a Tomcat server.
I tried to do Platform.runLater(this::foo); but I'm pretty sure it doesn't do anything. Probably because there's no JavaFX thread to do it.
I'd rather not open a ScheduledExecutorService because it's going to be another thread on many instances (so many threads), not to mention the method it would need to run is synchronized so I smell a deadlock.
I couldn't find any useful methods on Thread.currentThread() (run and start don't take parameters).
Is there another option to do this?
I used a newSingleThreadExecutor to achieve this, since it can take multiple runnables to a queue and run them sequentially, it can be given tasks from several places and it will run them one by one, it's similar to platform.runLater.
Having a single thread that all instances of the class hold a reference to, solves the "many threads" problem.
It also won't cause a deadlock because it will at most wait for just one other thread to finish the synchronized function and then run just this one function.

How to stop the execution of the method in the thread in Java?

I have J2EE project which uses framework struts2 and Tomcat. There are two actions: "start task" and "stop task". As I understand it, when a user runs the task "start task", then Tomcat starts a thread where the task is executed. The user can click "stop task" and then Tomcat starts the second thread where it needs to stop the first thread. Method of action where execute task very big. There are queries to DB and calculations. In order to stop thread I use interrupt() of first thread but interrupt() just change value of flag but the code in the method continues to run. I check interrupt flag (Thread.currentThread().isInterrupted()) in different parts of method and if thread is interrupted then I use "return". Is there any other way?
Your implementation is correct. The way you are using is recommended. Other way is to use Thread.stop() but this method is deprecated since java 1.1 and no-one should use it. This method is like kill -9 in Unix, i.e. it just kills the thread that may cause program to enter inconsistent state and can produce resource leak.
Obviously you can improve your design. You said that the method is very big. Generally method should not exceed 20 lines. Well, 50 is the maximum. If your method is so big, break it into smaller tasks and check isInterrupted() before each task.
Going forward to the OO world: create interface Task with method perform(). (Names do not matter. You can choose other names).
Each subtask should be implemented in separate class and should implement this interface. Then Create special InterruptionChecker that implements Task and holds other task. It checks whether thread is interrupted and if not, runs payload task. This pattern is called wrapper or decorator.
Now your "big" method should just run all tasks in loop. When thread is iterrupted the no new tasks is performed.

java: Patterns for Monitoring worker threads?

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.

What is the correct way to perform long-running operation outside the EDT?

In a desktop Java 1.5 application (it has to run on a lot of MacOS X machines that will nerver see a 1.6 VM due to Apple politics) what is a correct way to perform a lengthy computation outside the EDT?
Say, for example, when the user clicks on a button that starts an operation: I get the notification on the EDT and I want to run some method (say crunchData()).
Here's one way to do it:
final Thread t = new Thread( new Runnable() {
public void run() {
crunchData();
}
} );
t.start;
I mean: this does what I want but every single time the user starts a potentially long running task I use the above idiom. And I feel like I'm always unnecessarily creating lots of task (moreover although sometimes the operation can be lengthy, sometimes it won't and in these case I'd like the app as responsible as possible).
Another way to do it would be to have another (non-EDT) thread (or a pool of threads), always running, say waiting on a blocking queue and executing, say, Runnable that I would enqueue wherever I need to perform a lengthy operation.
What is the correct way to deal with this?
EDIT: Is the correct way to deal with something that simple to install SwingWorker? How did people deal with this (which seems pretty basic) before SwingWorker came?
The recommended way is to have your EDT code start a SwingWorker, which will do the job outside and return the result to you.

Java GUI, need to pause a method without freezing GUI aswell

I know that this problem is caused by the sleep or wait calling on the main thread and that the answer on how to solve this will be to put the method into a seperate thread and then make that thread sleep. But the code is a mess and don't really have the time to sort it out and split it up into separate threads and was wondering if there is any other way of doing this? Even if it is not the cleanest or most common practice for working with GUIs. I only need about a seconds pause from the method.
You can't do it without creating a separate thread. Creating a thread in Java is easy. The only thing to pay attention to is that you can only touch the UI through the main thread. For this reason you need to use something like SwingUtilities.invokeLater().
It is not possible to sleep on an event thread and not cause a GUI freeze. However in Swing, the event thread is created and managed behind the scenes - you main thread (the one originating from main() method) is not the event thread.
So, you can safely sleep on your main thread.
Using a separate thread for the code is your only solution. Every action started by the Swing thread must be delegated to a separate thread if it would otherwise block the GUI.
I wrote a super simple delay function for java that doesn't let your GUI freeze . It has worked everytime i have used it and i guess it will work for you too.
void Delay(Long ms){
Long dietime = System.currentTimeMillis()+ms;
while(System.currentTimeMillis()<dietime){
//do nothing
}
}
For eg : To delay a thread by 5 millisecods use Delay(5L)
And where would one declare this thread. Please bear in mind any, any reference to a function that contains thread sleep will cause the main thread to pause. Because the main thread will have to wait the the sub thread to pause.
The reality is that threads don't realy work as seperate independant thread because a thread must be started from another thread. In other words if you are creating desktop application, and even if you don't work with other threads, your application is a one threaded application. Now if you start working with threads & putting them to sleep, you will soon find out that that you won't be able to do anything else in the application. No & no the other threads won't even run because they are waiting the first thread to finish sleeping. Why is this? Cause the thread are sub threads of the main thread and it is the main thread that is waiting for that sleep sub thread to wake up. You can't design a threadless application either as java is single main threaded application. Any, yes any, thread further defined in your application always runs inside in the main thread.
Unless somebody can prove me wrong, you obviously whould never pause your main thread as this would lock up your app. However as soon you define another thread and suspend it with sleep() this also locks up your app as the thread was defined in subclass of the main application and therefore the main thread.
So to put a very very long story to bed, pausing a user defined thread, is almost exactly the same as if your called the Thread.sleep() for anywhere in your app, it
pauses the entire application.

Categories

Resources