Java EE WebListener and Thread - java

I've a servlet tagged as #WebListener.
public void contextInitialized(ServletContextEvent event) {
schedulerEngine = Executors.newSingleThreadScheduledExecutor();
schedulerEngine.scheduleAtFixedRate(new Batch1(), 0, MILLISECONDS_ITERATE_PA, TimeUnit.MILLISECONDS);
schedulerEngine.scheduleAtFixedRate(new Batch2(), 0, MILLISECONDS_ITERATE_IAS, TimeUnit.MILLISECONDS);
schedulerEngine.scheduleAtFixedRate(new Batch3(), 0, MILLISECONDS_ITERATE_EV1, TimeUnit.MILLISECONDS);
schedulerEngine.scheduleAtFixedRate(new Batch4(), 0, MILLISECONDS_ITERATE_MV1, TimeUnit.MILLISECONDS);
schedulerEngine.scheduleAtFixedRate(new Batch5(), 0, MILLISECONDS_ITERATE_BB, TimeUnit.MILLISECONDS);
schedulerEngine.scheduleAtFixedRate(new Batch6(), 0, MILLISECONDS_ITERATE_EV, TimeUnit.MILLISECONDS);
}
public class BatchX implements Runnable {
#Override
public void run() {
....
}
}
The MILLISECONDS_ITERATE_XX = 60000 (1 minute).
Is it possible that some thread stop itself for memory problems?
If in my BatchX() run method I have an exception (for example NullPointerException), the thread stop forever?

It is always possible for a block of code to be interrupted by an exception. Whether this is fatal or not depends on what measures you take to prevent or recover from them:
For checked exceptions e.g. IOException, you will need to put some recovery and/or logging code in your catch block and then decide if you wish to exit the method or continue executing.
In the case of unchecked exceptions e.g. NullPointerException it's best to prevent them, not catch them, for example by making sure that no object can be null when you try to access it, or that no index may exceed the bounds of an array when iterating, etc.
Edit: To answer your particular question, the Javadoc says:
If any execution of the task encounters an exception, subsequent
executions are suppressed. Otherwise, the task will only terminate via
cancellation or termination of the executor.

Related

Stop a method in java

I have made a method to send an e-mail, and I wanted to try if it was possible to call a method inside the method itself with a timer, to do like a scheduler
public void createExcel(){
int year = Calendar.getInstance().get(Calendar.YEAR);
int num_week = data.getCurrentWeek()-1;
ArrayList<DHDemande> ListeDemandes = d.getDemandesForPaie(num_week, year);
try {
data.createFile(ListeDemandes);
Thread.sleep(20000);
createExcel();
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
But now the method doesn't stop (it was obvious) but even if I refresh Apache and if I change the method. How can I stop it ? because I receive an email every 20 second now
The thing with Treads is that there is now save way to tell it to just stop without memory leaks. You can use thread.stop(), this will kill the thread but it may cause memory problems if your objects are too big.
Quote from java doc:
stop() Deprecated. This method is inherently unsafe. Stopping a
thread with Thread.stop causes it to unlock all of the monitors that
it has locked (as a natural consequence of the unchecked ThreadDeath
exception propagating up the stack). If any of the objects previously
protected by these monitors were in an inconsistent state, the damaged
objects become visible to other threads, potentially resulting in
arbitrary behavior. Many uses of stop should be replaced by code that
simply modifies some variable to indicate that the target thread
should stop running. The target thread should check this variable
regularly, and return from its run method in an orderly fashion if the
variable indicates that it is to stop running. If the target thread
waits for long periods (on a condition variable, for example), the
interrupt method should be used to interrupt the wait. For more
information, see Why are Thread.stop, Thread.suspend and Thread.resume
Deprecated?.
Explore the Thread api and see if you can find anything else that suites your needs.
As Borislav mentioned, stop() is incorrect here, you need to call and handle interrupt().
class Test
{
public static Thread helloWorldLater()
{
Thread t = new Thread(new Runnable(){
#Override public void run()
{
try {
Thread.sleep(200);
System.out.println("Hello World");
}
catch(InterruptedException ex)
{
// clean up here
return;
}
}
});
t.start();
return t;
}
public static void main(String[] args) throws InterruptedException
{
Thread t = helloWorldLater();
Thread.sleep(100);
t.interrupt();
// no "Hello World" to be seen
}
}
Alternatively, depending on your Java version, you can also use the more modern concurrency Java APIs.
Besides Borislavs and Konrads legitimate comments on thread.stop(), you are calling the createExcel() method recursively (after Thread.sleep(20000)), so obviously your method will run forever. If you remove that call it should work like you expect it.

Java: Waiting on Get Method of ScheduledFuture

Please consider the following code:
public static void main(String... args) throws InterruptedException, ExecutionException {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> future =
executor.scheduleAtFixedRate(Dummy::iterate,
0,
1,
TimeUnit.SECONDS);
TimeUnit.MILLISECONDS.sleep(1500);
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MILLISECONDS);
System.out.println("Getting the future...");
future.get();
System.out.println("Got the future...");
System.out.println("Finished");
}
private static void iterate(){
System.out.println("Iterating... counter is: " + counter++);
try {
TimeUnit.MILLISECONDS.sleep(900);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Note that the executor.awaitTermination(...) command future.get() command are happening after 1500 ms, meaning in the middle of the iterate() method.
This means that awaitTermination(...) will return false because the scheduled task hasn't finsihed yet.
Now, future.get() will wait forever. The task will finish and the service won't start other tasks, but yet the get() will never return.
A workaround is asking the future for isDone(), and only if it is done, asking for the result.
My question is what exactly is happening?
Looks like that if shutDown() happens in the during an iteration, the ScheduledThreadPool will somehow halt and, meaning there will be no future available. So why is this happening? I have looked at the documentation but couldn't find any reference indicating this issue. Is it possible that such scenario causes a future to not done, and later for the future to not be available?
If you replace your :
future.get();
to something like:
future.get(2000,TimeUnit.MILLISECONDS);
Then you see java.util.concurrent.TimeoutException exception ocuur.
and this Exception thrown when a blocking operation times out. Blocking operations for which a timeout is specified need a means to indicate that the timeout has occurred. For many such operations it is possible to return a value that indicates timeout; when that is not possible or desirable then TimeoutException should be declared and thrown.

Why restore interrupt flag of a task that ran in a thread pool's thread

This snippet is from JCIP (Brian Goetz) listing 6.15
f.get() throws InterruptedException and ExecutionException. Now, these exceptions are specific to the future correct?
Meaning the specific task represented by the future was interrupted or had an internal exception.
Questions -
Why do I need to restore the interrupt using "Thread.currentThread().interrupt()"? , because isnt the interrupt flag for the thread my task ran in? This is a little confusing.
Why throw launderThrowable exception? If one of the downloadImage had an issue, shouldnt we just process the other downloaded images intead of throwing from here and thus just "not" processing the remaining futures?
package net.jcip.examples;
import java.util.*;
import java.util.concurrent.*;
import static net.jcip.examples.LaunderThrowable.launderThrowable;
/**
* Renderer
* <p/>
* Using CompletionService to render page elements as they become available
*
* #author Brian Goetz and Tim Peierls
*/
public abstract class Renderer {
private final ExecutorService executor;
Renderer(ExecutorService executor) {
this.executor = executor;
}
void renderPage(CharSequence source) {
final List<ImageInfo> info = scanForImageInfo(source);
CompletionService<ImageData> completionService =
new ExecutorCompletionService<ImageData>(executor);
for (final ImageInfo imageInfo : info)
completionService.submit(new Callable<ImageData>() {
public ImageData call() {
return imageInfo.downloadImage();
}
});
renderText(source);
try {
for (int t = 0, n = info.size(); t < n; t++) {
Future<ImageData> f = completionService.take();
ImageData imageData = f.get();
renderImage(imageData);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
throw launderThrowable(e.getCause());
}
}
interface ImageData {
}
interface ImageInfo {
ImageData downloadImage();
}
abstract void renderText(CharSequence s);
abstract List<ImageInfo> scanForImageInfo(CharSequence s);
abstract void renderImage(ImageData i);
}
When you catch InterruptedException interrupted flag gets reset and your thread is technically not interrupted anymore. However, you don't know if the code that called your code (or other code in the same thread), requires any additional interrupt handling. By calling interrupt() you raise the flag again and effectively saying to the rest of the application "This thread is still interrupted - act on it if necessary".
Consider example. You method is called from the loop that must terminate if thread is interrupted. You caught the exception and if you don't raise the flag, the loop will not terminate as required.
By catching InterruptedException, you are stopping the interruption from reaching the Thread in which you are running. But you want it to reach it, in case there is any special processing the Thread needs to do in case of interruption - you can't tell, so you'd better play it safe and allow it to percolate up. You may do some processing yourself (to clean up, exit what you are doing, etc), but you must pass it on. The best way to do this is to call Thread.currentThread().interrupt().
The interruption does not necessarily happen on the thread pool's thread. The interruption is for a point when your current thread is interrupted while you are waiting on the future's get to complete. For instance, if you made the Future accessible to another part of the program that can cancel the download, then Future.cancel(true) will cause that InterruptedException to occur which you can then clean up the rest of the data. And as Beohemaian mentioned, it is always safe to propogate the interruption.
Thats a good question. I think that was more of a design choice of what he wanted it to do. But you can easily hold onto that error and throw it after the rest complete. Something to think about though, what if its an OutOfMemoryError? Then the launder would be useful to only throw if its an Error and maybe not a RuntimeException.

Why invoke Thread.currentThread.interrupt() in a catch InterruptException block?

Why invoke the method Thread.currentThread.interrupt() in the catch block?
This is done to keep state.
When you catch the InterruptedException and swallow it, you essentially prevent any higher-level methods/thread groups from noticing the interrupt. Which may cause problems.
By calling Thread.currentThread().interrupt(), you set the interrupt flag of the thread, so higher-level interrupt handlers will notice it and can handle it appropriately.
Java Concurrency in Practice discusses this in more detail in Chapter 7.1.3: Responding to Interruption. Its rule is:
Only code that implements a thread's interruption policy may swallow an interruption request. General-purpose task and library code should never swallow interruption requests.
I think this code sample makes things a bit clear.
The class which does the job :
public class InterruptedSleepingRunner implements Runnable {
#Override
public void run() {
doAPseudoHeavyWeightJob();
}
private void doAPseudoHeavyWeightJob() {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
// You are kidding me
System.out.println(i + " " + i * 2);
// Let me sleep <evil grin>
if (Thread.currentThread().isInterrupted()) {
System.out.println("Thread interrupted\n Exiting...");
break;
} else {
sleepBabySleep();
}
}
}
protected void sleepBabySleep() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
The Main class:
public class InterruptedSleepingThreadMain {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new InterruptedSleepingRunner());
thread.start();
// Giving 10 seconds to finish the job.
Thread.sleep(10000);
// Let me interrupt
thread.interrupt();
}
}
Try calling interrupt without setting the status back.
Note:
http://download.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
How do I stop a thread that waits for long periods (e.g., for input)?
For this technique to work, it's critical that any method that catches an interrupt exception and is not prepared to deal with it immediately reasserts the exception. We say reasserts rather than rethrows, because it is not always possible to rethrow the exception. If the method that catches the InterruptedException is not declared to throw this (checked) exception, then it should "reinterrupt itself" with the following incantation:
Thread.currentThread().interrupt();
This ensures that the Thread will reraise the InterruptedException as soon as it is able.
I would consider it a bad practice or at least a bit risky.
Usually higher level methods do not perform blocking operations and they will never see InterruptedException there. If you mask it in every place you perform interruptible operation, you will never get it.
The only rationale for Thread.currentThread.interrupt() and not raising any other exception or signaling interrupt request in any other way (e.g. setting interrupted local variable variable in a thread's main loop) is the situation where you really can't do anything with the exception, like in the finally blocks.
See Péter Török's answer, if you want to better understand implications of the Thread.currentThread.interrupt() call.
Refer from java doc
If this thread is blocked in an invocation of the wait(), join(),
sleep(long), then its interrupt status will be cleared and it will
receive an InterruptedException.
If this thread is blocked in an I/O operation, the thread's interrupt
status will be set, and the thread will receive a
ClosedByInterruptException.
If this thread is blocked in a Selector then the thread's interrupt
status will be set and it will return immediately from the selection
operation.
If none of the previous conditions hold then this thread's interrupt
status will be set.
So, if you change the sleepBabySleep() method in #Ajay George Answer to I/O operation or just a sysout, you don't have to set the status back to stop the program. (BTW, they don't even throw InterruptedException)
Just like #Péter Török said => This is done to keep state. (And particular for method that will throw InterruptedException)

On FutureTask, finally and TimeoutExceptions in Java

I'm trying to understand how to ensure that a specific action completes in a certain amount of time. Seems like a simple job for java's new util.concurrent library. However, this task claims a connection to the database and I want to be sure that it properly releases that connection upon timeout.
so to call the service:
int resultCount = -1;
ExecutorService executor = null;
try {
executor = Executors.newSingleThreadExecutor();
FutureTask<Integer> task = new CopyTask<Integer>();
executor.execute(task);
try {
resultCount = task.get(2, TimeUnit.MINUTES);
} catch (Exception e) {
LOGGER.fatal("Migrate Events job crashed.", e);
task.cancel(true);
return;
}
} finally {
if (executor != null) {
executor.shutdown();
}
The task itself simply wrapps a callable, here is the call method:
#Override
public Integer call() throws Exception {
Session session = null;
try {
session = getSession();
... execute sql against sesssion ...
}
} finally {
if (session != null) {
session.release();
}
}
}
So, my question for those who've made it this far, is: Is session.release() garaunteed to be called in the case that the task fails due to a TimeoutException? I postulate that it is no, but I would love to be proven wrong.
Thanks
edit: The problem I'm having is that occasionally the sql in question is not finishing due to wierd db problems. So, what I want to do is simply close the connection, let the db rollback the transaction, get some rest and reattempt this at a later time. So I'm treating the get(...) as if it were like killing the thead. Is that wrong?
When you call task.get() with a timeout, that timeout only applies to the attempt to obtain the results (in your current thread), not the calculation itself (in the worker thread). Hence your problem here; if a worker thread gets into some state from which it will never return, then the timeout simply ensures that your polling code will keep running but will do nothing to affect the worker.
Your call to task.cancel(true) in the catch block is what I was initially going to suggest, and this is good coding practice. Unfortunately this only sets a flag on the thread that may/should be checked by well-behaved long-running, cancellable tasks, but it doesn't take any direct action on the other thread. If the SQL executing methods don't declare that they throw InterruptedException, then they aren't going to check this flag and aren't going to be interruptable via the typical Java mechanism.
Really all of this comes down to the fact that the code in the worker thread must support some mechanism of stopping itself if it's run for too long. Supporting the standard interrupt mechanism is one way of doing this; checking some boolean flag intermittently, or other bespoke alternatives, would work too. However there is no guaranteed way to cause another thread to return (short of Thread.stop, which is deprecated for good reason). You need to coordinate with the running code to signal it to stop in a way that it will notice.
In this particular case, I expect there are probably some parameters you could set on the DB connection so that the SQL calls will time out after a given period, meaning that control returns to your Java code (probably with some exception) and so the finally block gets called. If not, i.e. there's no way to make the database call (such as PreparedStatement.execute()) return control after some predetermined time, then you'll need to spawn an extra thread within your Callable that can monitor a timeout and forcibly close the connection/session if it expires. This isn't very nice though and your code will be a lot cleaner if you can get the SQL calls to cooperate.
(So ironically despite you supplying a good amount of code to support this question, the really important part is the bit you redacted: "... execute sql against sesssion ..." :-))
You cannot interrupt a thread from the outside, so the timeout will have no effect on the code down in the JDBC layer (perhaps even over in JNI-land somewhere.) Presumably eventually the SQL work will end and the session.release() will happen, but that may be long after the end of your timeout.
The finally block will eventually execute.
When your Task takes longer then 2 minutes, a TimeoutException is thrown but the actual thread continues to perform it's work and eventually it will call the finally block. Even if you cancel the task and force an interrupt, the finally block will be called.
Here's a small example based in your code. You can test these situations:
public static void main(String[] args) {
int resultCount = -1;
ExecutorService executor = null;
try {
executor = Executors.newSingleThreadExecutor();
FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() {
#Override
public Integer call() throws Exception {
try {
Thread.sleep(10000);
return 1;
} finally {
System.out.println("FINALLY CALLED!!!");
}
}
});
executor.execute(task);
try {
resultCount = task.get(1000, TimeUnit.MILLISECONDS);
} catch (Exception e) {
System.out.println("Migrate Events job crashed: " + e.getMessage());
task.cancel(true);
return;
}
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
Your example says:
copyRecords.cancel(true);
I assume this was meant to say:
task.cancel(true);
Your finally block will be called assuming that the contents of the try block are interruptible. Some operations are (like wait()), some operations are not (like InputStream#read()). It all depends on the operation that that the code is blocking on when the task is interrupted.

Categories

Resources