What part of my code is in the event dispatch queue - java

I thought I understood EDQ until I hit this problem. I have the code shown below. It reads from a Bufferred reader. If the first character received is a "Z" I execute one set of code (displaying a JOptionPane) and if it is a 0 I execute another section of code (displaying another JOptionPane). I am trying to do this within the EDQ and so I use SwingUtilities invokeAndWait. When I test these error conditions, the first statement in the conditional works as designed, but I get a java error when testing the else clause. Specifically:
Exception in thread "AWT-EventQueue-2" java.lang.Error: Cannot call invokeAndWait from the event dispatcher thread
at java.awt.EventQueue.invokeAndWait(Unknown Source)
It is all part of the same conditional. How can one clause be part of the EDQ and another clause not be.
This is crazy.
Thanks for any help.
Elliott
while ((line = in.readLine()) != null) {
if (line.charAt(0) == 'Z') {
String theMsg;
theMsg = "No records were found.";
try {
SwingUtilities.invokeAndWait(new DoShowDialog(null, theMsg, 0));
} catch (java.lang.reflect.InvocationTargetException e1) {
e1.printStackTrace();
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
noDocs = true;
Object args[] = new Object[1];
args[0] = "1";
window.call("uploadConfig", args);
downloadAccount.setEnabled(true);
uploadAccount.setEnabled(false);
deleteAllUnselectedCodes.setEnabled(false);
queue = null;
if (poll) {
polltimer.restart();
}
} else if (line.charAt(0) == 'O') {
String theMsg;
theMsg = "Account is currently checked out
by user "+ line.substring(1)
+ ". You can view this
account but you cannot modify it. ";
try {
SwingUtilities.invokeAndWait(new DoShowDialog(null, theMsg, 0));
} catch (java.lang.reflect.InvocationTargetException e1) {
e1.printStackTrace();
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
initialckBoxState = false;
accountfoundandnotcheckedout = true;
viewMode = true;
patientpane.setEditFields(false);
otherpane.setEditFields(false);
getAccountImages(acctEntered); // bluenoble
}
.....................
more stuff
}

Execution doesn't jump threads.
Thus all the code posted runs in the EDT (Event Dispatch Thread) and it refuses to invokeAndWait because that causes an inherent deadlock. (Actually, it could be turned into an invoke-immediate as done with SynchronizationContexts in .NET, but it was not designed as such.)
In this particular case I suspect the code is invoked from within an EDT callback (and copy'n'pasted from another scenario). The "trivial fix" (that would eliminate this exception) would be to eliminate the invokeAndWait methods, but that will have a negative impact if this code is invoked off the EDT as well -- the two situations much be handled differently. Take some time to determine when/where this code will run, and why.
As others have pointed out, this code seems confused: if it's off the EDT, manipulating Swing objects is bad, and if it's on the EDT then there is no need to invokeAndWait and blocking is bad.
Happy coding.

if that is eventually called from a event handler then it is called from the EDT (all your code will be unless you use swingworkers or explicitly create thread/use threadpools)
check the stack trace to find were it comes from
to fix it use aforementioned SwingWorker and override doInBackground() and you can check whether you are in the dispatch thread with SwingUtilities.isEventDispatchThread()

1) theMsg look like crazy theMsg = "someString" + localVariable + "anotherString"
2a) why did you call Swing GUI inside Basic File I/O
2b) why did you build GUI inside Basic File I/O
read File, close(); I/O Stream in finally block
3) you create lots of DoShowDialog(null, theMsg, 0));, every loop create one, and etc
4) every true and false move outside this I/O Stream
5) load every events to the some of Array, if I/O Stream
6) you code probably freeze GUI, if exist
7) move all Stream to the BackGround Task

Related

Deadlock occurring when using java.nio.file.Paths & jsfml loadFromFile

I've been trying to debug a problem I've had with loading a font from file (a .ttf file) with the java.nio.file.Paths import, using a combination of Paths.get() and loadFromFile(), but can't seem to find a solution.
Here's the problem code:
import java.io.IOException;
import java.nio.file.Paths;
public final Font FONT_UI_BAR = new Font();
public final Font FONT_FREESANS = new Font();
try {
System.out.println("We get here, before loading");
FONT_UI_BAR.loadFromFile(Paths.get("Game/resources/UI/Font.ttf"));
System.out.println("I've loaded the first font");
FONT_FREESANS.loadFromFile(Paths.get("Game/resources/fonts/freesans/freesans.ttf"));
} catch (IOException e2) {
System.out.println("[ERROR] Could not load font");
e.printStackTrace();
}
The program gets to the first print statement but never reaches the second.
I did a thread dump and found there seems to be a deadlock within the code itself that occurs:
"main#1" prio=5 tid=0x1 nid=NA waiting
java.lang.Thread.State: WAITING
at jdk.internal.misc.Unsafe.park(Unsafe.java:-1)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:194)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:885)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1039)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1345)
at java.util.concurrent.Semaphore.acquire(Semaphore.java:318)
at org.jsfml.internal.SFMLErrorCapture.start(Unknown Source:-1)
at org.jsfml.graphics.Font.loadFromFile(Unknown Source:-1)
at assets.FontCatalogue.<init>(FontCatalogue.java:32)
at assets.FontCatalogue.get(FontCatalogue.java:15)
at screens.HomeScreen.<init>(HomeScreen.java:51)
at controllers.Game.<init>(Game.java:74)
at Main.main(Main.java:16)
I'm not exactly sure how to proceed from here. My program won't function how I want it to without loading these fonts. I've tried loading other kinds of fonts and the problem persists.
Weirdly enough the problem didn't occur with loading other files in the past, such as this code:
TEMP_BG_01.loadFromFile(Paths.get("Game/resources/placeholder/full-moon_bg.png"));
It only started once I started trying to load these fonts.
Ideally I'd like to find a solution that still allows me to use this package because otherwise I have a fair amount of code to rewrite. Not the biggest deal but suggesting simply using another package should be a last resort.
Any ideas appreciated.
EDIT: Interesting to note this issue DOES NOT occur on a Windows machine, only my ubuntu-linux one. The rest of my team on Windows have no issues. Obviously one solution is to go and use Windows instead, but who wants to do that :p
EDIT #2: Turns out I'm now getting this error even with loading from the Texture class in JSFML. I have a feeling I updated my JVM when I updated my ubuntu sometime recently and that's suddenly introduced problems. I can't say for sure because I don't recall updating very recently, but it seems as of 21/02/2021 loading from file with JSFML causes a deadlock :/
The first thing you need to do if you want to continue using JSFML is to determine the initial failure that leaves you in a deadlock state.
The code in the SFMLErrorCapture class is not robust. Should SFMLErrorCapture.start() fail in any way, it will leave the semaphore locked. I suspect this is the initial failure that breaks your application and leaves it deadlocked.
I'd recommend adding logging to the class, such as:
public static void start() {
try {
semaphore.acquire();
capturing = true;
nativeStart();
} catch (InterruptedException ex) {
ex.printStackTrace();
} catch (Throwable t) {
t.printStackTrace();
// lots of other logging, probably to a file in /tmp
// rethrow so original program flow isn't changed
throw t;
}
}
You might also want to add more logging to see if you get any InterruptedExceptions. That's another way the semaphore will never get released, but I don't think a simple upgrade is likely to trigger that kind of behavior change.
And, since it's also possible for finish() to fail in the same manner (such as if nativeFinish() returns null, which I'd think is also a likely failure mode...):
public static String finish() {
try {
final String str;
if (capturing) {
str = nativeFinish().trim();
capturing = false;
semaphore.release();
} else {
str = null;
}
return str;
} catch (Throwable t) {
t.printStackTrace();
// lots of logging
throw t;
}
}
You might need to add throws Throwable to both methods.
This might also help:
public static String finish() {
try {
final String str;
if (capturing) {
// chaining calls is BAD CODE!!!!
// Say hello to NPE if you insist cramming
// multiple calls in one line!!
str = nativeFinish();
if ( str != null ) {
str = str.trim();
}
capturing = false;
semaphore.release();
} else {
str = null;
}
return str;
}
}
Limiting asynchronous actions like this to one at a time is fundamentally broken. If only one action can happen at once, the code complexity added to do actions asynchronously is worse than wasted because such complex code is much more bug-prone and when bugs do happen that complexity makes unrecoverable failures much more likely.
If you can only do one at a time, just do the actions serially with one static synchronized method or in one synchronized block on a static final object.

threading infinity loop java

Inside a method, I start a thread that waits for user input (swing pushbutton).
Only after that input, the thread can be closed and the method returns a value.
My problem is that the code waiting for the input is not run inside that thread, but elsewhere:
String returnString = "";
Thread waitThread = new Thread(
() -> {
while (xy == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw THREAD_INTERRUPTED.toException();
}
}
}, "waitThread"
);
waitThread.start();
try {
waitThread.join();
} catch (InterruptedException e) {
throw THREAD_INTERRUPTED.toException();
}
// -> wait for user input -> xy != null -> waitThread ends -> main thread joins -> continue code:
returnString = xy;
return ReturnString;
Why is this necessary? Because the method has to return the value (xy) that is set elsewhere by clicking a pushbutton.
The code above just ends up in an infinity loop, not allowing any interaction with the swing components.
Not being a pro in swing, I suppose the main thread is meant to catch interaction events. Since it is stuck in the waitThread.join(); , thats not possible. Correct?
Is there a way to restructure this?
Why reinvent the wheel? Plenty of ways to do this out-of-the-box:
public static void main(String[] args) {
String message = JOptionPane.showInputDialog("What are you gonna tell me?");
System.out.println(message);
}
I think you are going down the wrong route.
Clicking a button leads to an event, and then there should be an ActionListener reacting to that.
And that listener could update some "statish" thingy, and your other thread is reading that information.
To answer jannis' question: The method opens a popup window that holds lets say two buttons. Each button sets a specific return value for the popup, which is then returned by the same method. So the method needs to open and close the popup. I know this is stupid, but it has to be this way. The setup would work, if I could keep interaction with the frontend enabled while waiting somehow.
Judging from this comment you seem to be trying to rediscover what is called a "modal dialog" and it's not stupid, at all. Please see the official documentation about dialogs in Swing: How to Make Dialogs
.

Delaying 8 Seconds not working?

So, I am trying to send a packet (With Spigot) every 8 seconds.
I would post this on the Spigot forums but I always get the error on the wait. I have tried Scheduler but no luck.
Code:
Object obj = new Object();
try {
synchronized (obj) {
while (true) {
for (Player player : Bukkit.getOnlinePlayers()) {
System.out.println("Hi");
obj.wait(8000);
}
}
}
} catch (InterruptedException exception) {
}
Ignore the Player player thing it does nothing.
Help please. Any help is appreciated.
wait() is a method intended for asynchronous programming, where you let a chunk of code run while something else "needs time" to finish, as to not block the whole execution of the program. Think of it as a a mechanism that lets asynchronous things happen. As per the docs:
Causes the current thread to wait until another thread invokes the
notify() method or the notifyAll() method for this object.
Whereas sleep() is a method that makes the current thread stand by for a moment until the desired time has passed and so it will continue its execution:
Thread.sleep causes the current thread to suspend execution for a
specified period.
The former is useful in asynchronous programming, where you know something will potentially block execution of your program for a while and you want to do other stuff in that time, like connecting to a socket, probably all in the same thread. The latter is when you want to stop everything from happening for a moment on the same thread.
If what you want to do is just delay the execution of your method, then this would be the way to go:
try {
while (true) {
for (Player player : Bukkit.getOnlinePlayers()) {
System.out.println("Hi");
Thread.sleep(8000);
}
}
} catch (InterruptedException exception) {
// Catch something here
}

Java concurrency - Is this efficient?

System.out.println("Enter the number of what you would like to do");
System.out.println("1 = Manually enter Options");
System.out.println("2 = Use a text file to pick from pre-existing models");
System.out.println("3 = Exit ");
Scanner sc = new Scanner(System.in);
try {
runType = sc.nextInt();
if(runType > 3) {
throw new badValue(999, "Not the valid input");
}
} catch (NullPointerException e) {
} catch (badValue e) {
e.correctBadValue(runType);
}
switch (runType) {
case 1:
Thread a = new SelectCarOption();
a.run();
case 2:
Thread a2 = new BuildCarModelOptions();
a2.run();
case 3:
System.exit(1);
}
}
}
So basically, I'm trying to run a program where the thread that is running is determined by a variable runType. If runType is one value, a certain thread will run and if it is the other, the other will run. Is my approach the most efficient? Will it turn out to give any errors?
Long story short, no, this is not how you want to do things.
thread1.run() doesn't start a new thread, it just calls the code in run() on the current thread. What you want is thread1.start().
thread1.sleep(5000) will not make thread1 sleep, it will make the main thread sleep. Thread.sleep is a static method that affects the current thread, and the fact that you're using an instance variable to invoke it (rather than the more traditional Thread.sleep(5000)) doesn't change that.
It makes no sense to start thread2 and then immediately join to it. You may as well just invoke its code directly on the main thread. (Which is what you're doing right now, since you're invoking thread2.run() instead of thread2.start().)
I'm not sure what your end goals are, but this sounds like a case for plain old polymorphism. Create a Runnable and assign it to one of two concrete implementations, depending on the input; then just invoke run() on it. Something like:
Runnable selectStrategy = (runType == 2)
? new CarModelOptionsIO()
: new SelectCarOption()
selectStrategy.run()
If you need a result from this action, you could use a Callable<T> (don't let the package name confuse you; there's nothing inherent to concurrency in that interface) or even create your own interface, which lets you give more meaningful names to the methods (call and run are pretty unhelpfully generic).
A programmer had a problem. He thought to himself, "I know, I'll solve it with threads!". has Now problems. two he
A)
you can replace
Thread thread1 = new SelectCarOption();
thread1.start();
thread1.join();
by directly executing whatever run does since the thread that starts the thread just waits.
calling thread | new thread
start() ---->
run()
join() <---
does the same thing as
run()
Now we can simplify your code to:
if (runType == 2) {
doCarModelOptionsIO();
} else {
doSelectCarOption()
}
And you have a much more efficient way.
B)
Don't call the run() method on a thread. Every method called directly is executed in place in your current thread. Thread has the start() method that you call which then calls run() from within that new thread.
Overall, your code is confused. I suggest reading the concurrency tutorials if you haven't already. Review them if you have read them. Maybe do a few yourself, then come back to this problem.
You say:
If runType is one value, a certain thread will run and if it is the other, the other will run.
To do that you need something like this...
if (runType == 2) {
Thread thread1 = new SelectCarOption();
thread1.run();
try {
//join blocks until thread 1 terminates. We don't know that it
//ever will give your code
thread1.join(); //stops thread1 to run different thread
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Thread thread2 = new CarModelOptionsIO();
thread2.run();
try {
//blocks again, until thread 2 is done running.
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
//start some other thread here since runType is different?
}
There are many mistakes in your class. First you are using the method run() instead of start(). Second, you should start both threads for your sleep() make sense. That a look on the Oracle Java Se tutorial online to see the basics of Java Multithreading model, that will help a lot.
There are several mistakes in your code. and to let you know, the code you have written does not spawn a new thread at all. Few thing to note:
Thread.sleep() is a static method. The below code is misleading:
try {
thread1.sleep(5000); //stops thread1 to run different thread
} catch (InterruptedException e1) {
e1.printStackTrace();
}
You have started thread1 in the main thread and then called sleep method using the newly created thread. But this is not gonna help you. It makes the main thread sleep not thread1. To make thread1 sleep you need to call sleep method within the run() of this thread1 class.
Moreover, sleep() is a static method and should not be called using thread instances, it is misleading.
Also stopping a thread does not necessarily mean it will invoke the other thread. Just remember when it comes to threading, very little is guaranteed.
One more thing :
thread1.run(); // This is incorrect
use thread1.start()
Directly calling run() method does not start a new thread. You need to call start() method to start a new thread. Calling run method directly will execute the contents of the run method in the same thread(from where it is invoked)

How can I wrap a method so that I can kill its execution if it exceeds a specified timeout?

I have a method that I would like to call. However, I'm looking for a clean, simple way to kill it or force it to return if it is taking too long to execute.
I'm using Java.
to illustrate:
logger.info("sequentially executing all batches...");
for (TestExecutor executor : builder.getExecutors()) {
logger.info("executing batch...");
executor.execute();
}
I figure the TestExecutor class should implement Callable and continue in that direction.
But all i want to be able to do is stop executor.execute() if it's taking too long.
Suggestions...?
EDIT
Many of the suggestions received assume that the method being executed that takes a long time contains some kind of loop and that a variable could periodically be checked.
However, this is not the case. So something that won't necessarily be clean and that will just stop the execution whereever it is is acceptable.
You should take a look at these classes :
FutureTask, Callable, Executors
Here is an example :
public class TimeoutExample {
public static Object myMethod() {
// does your thing and taking a long time to execute
return someResult;
}
public static void main(final String[] args) {
Callable<Object> callable = new Callable<Object>() {
public Object call() throws Exception {
return myMethod();
}
};
ExecutorService executorService = Executors.newCachedThreadPool();
Future<Object> task = executorService.submit(callable);
try {
// ok, wait for 30 seconds max
Object result = task.get(30, TimeUnit.SECONDS);
System.out.println("Finished with result: " + result);
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
System.out.println("timeout...");
} catch (InterruptedException e) {
System.out.println("interrupted");
}
}
}
Java's interruption mechanism is intended for this kind of scenario. If the method that you wish to abort is executing a loop, just have it check the thread's interrupted status on every iteration. If it's interrupted, throw an InterruptedException.
Then, when you want to abort, you just have to invoke interrupt on the appropriate thread.
Alternatively, you can use the approach Sun suggest as an alternative to the deprecated stop method. This doesn't involve throwing any exceptions, the method would just return normally.
I'm assuming the use of multiple threads in the following statements.
I've done some reading in this area and most authors say that it's a bad idea to kill another thread.
If the function that you want to kill can be designed to periodically check a variable or synchronization primitive, and then terminate cleanly if that variable or synchronization primitive is set, that would be pretty clean. Then some sort of monitor thread can sleep for a number of milliseconds and then set the variable or synchronization primitive.
Really, you can't... The only way to do it is to either use thread.stop, agree on a 'cooperative' method (e.g. occassionally check for Thread.isInterrupted or call a method which throws an InterruptedException, e.g. Thread.sleep()), or somehow invoke the method in another JVM entirely.
For certain kinds of tests, calling stop() is okay, but it will probably damage the state of your test suite, so you'll have to relaunch the JVM after each call to stop() if you want to avoid interaction effects.
For a good description of how to implement the cooperative approach, check out Sun's FAQ on the deprecated Thread methods.
For an example of this approach in real life, Eclipse RCP's Job API's 'IProgressMonitor' object allows some management service to signal sub-processes (via the 'cancel' method) that they should stop. Of course, that relies on the methods to actually check the isCancelled method regularly, which they often fail to do.
A hybrid approach might be to ask the thread nicely with interrupt, then insist a couple of seconds later with stop. Again, you shouldn't use stop in production code, but it might be fine in this case, esp. if you exit the JVM soon after.
To test this approach, I wrote a simple harness, which takes a runnable and tries to execute it. Feel free to comment/edit.
public void testStop(Runnable r) {
Thread t = new Thread(r);
t.start();
try {
t.join(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (!t.isAlive()) {
System.err.println("Finished on time.");
return;
}
try {
t.interrupt();
t.join(2000);
if (!t.isAlive()) {
System.err.println("cooperative stop");
return;
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.err.println("non-cooperative stop");
StackTraceElement[] trace = Thread.getAllStackTraces().get(t);
if (null != trace) {
Throwable temp = new Throwable();
temp.setStackTrace(trace);
temp.printStackTrace();
}
t.stop();
System.err.println("stopped non-cooperative thread");
}
To test it, I wrote two competing infinite loops, one cooperative, and one that never checks its thread's interrupted bit.
public void cooperative() {
try {
for (;;) {
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.err.println("cooperative() interrupted");
} finally {
System.err.println("cooperative() finally");
}
}
public void noncooperative() {
try {
for (;;) {
Thread.yield();
}
} finally {
System.err.println("noncooperative() finally");
}
}
Finally, I wrote the tests (JUnit 4) to exercise them:
#Test
public void testStopCooperative() {
testStop(new Runnable() {
#Override
public void run() {
cooperative();
}
});
}
#Test
public void testStopNoncooperative() {
testStop(new Runnable() {
#Override
public void run() {
noncooperative();
}
});
}
I had never used Thread.stop() before, so I was unaware of its operation. It works by throwing a ThreadDeath object from whereever the target thread is currently running. This extends Error. So, while it doesn't always work cleanly, it will usually leave simple programs with a fairly reasonable program state. For example, any finally blocks are called. If you wanted to be a real jerk, you could catch ThreadDeath (or Error), and keep running, anyway!
If nothing else, this really makes me wish more code followed the IProgressMonitor approach - adding another parameter to methods that might take a while, and encouraging the implementor of the method to occasionally poll the Monitor object to see if the user wants the system to give up. I'll try to follow this pattern in the future, especially methods that might be interactive. Of course, you don't necessarily know in advance which methods will be used this way, but that is what Profilers are for, I guess.
As for the 'start another JVM entirely' method, that will take more work. I don't know if anyone has written a delegating class loader, or if one is included in the JVM, but that would be required for this approach.
Nobody answered it directly, so here's the closest thing i can give you in a short amount of psuedo code:
wrap the method in a runnable/callable. The method itself is going to have to check for interrupted status if you want it to stop (for example, if this method is a loop, inside the loop check for Thread.currentThread().isInterrupted and if so, stop the loop (don't check on every iteration though, or you'll just slow stuff down.
in the wrapping method, use thread.join(timeout) to wait the time you want to let the method run. or, inside a loop there, call join repeatedly with a smaller timeout if you need to do other things while waiting. if the method doesn't finish, after joining, use the above recommendations for aborting fast/clean.
so code wise, old code:
void myMethod()
{
methodTakingAllTheTime();
}
new code:
void myMethod()
{
Thread t = new Thread(new Runnable()
{
public void run()
{
methodTakingAllTheTime(); // modify the internals of this method to check for interruption
}
});
t.join(5000); // 5 seconds
t.interrupt();
}
but again, for this to work well, you'll still have to modify methodTakingAllTheTime or that thread will just continue to run after you've called interrupt.
The correct answer is, I believe, to create a Runnable to execute the sub-program, and run this in a separate Thread. THe Runnable may be a FutureTask, which you can run with a timeout ("get" method). If it times out, you'll get a TimeoutException, in which I suggest you
call thread.interrupt() to attempt to end it in a semi-cooperative manner (many library calls seem to be sensitive to this, so it will probably work)
wait a little (Thread.sleep(300))
and then, if the thread is still active (thread.isActive()), call thread.stop(). This is a deprecated method, but apparently the only game in town short of running a separate process with all that this entails.
In my application, where I run untrusted, uncooperative code written by my beginner students, I do the above, ensuring that the killed thread never has (write) access to any objects that survive its death. This includes the object that houses the called method, which is discarded if a timeout occurs. (I tell my students to avoid timeouts, because their agent will be disqualified.) I am unsure about memory leaks...
I distinguish between long runtimes (method terminates) and hard timeouts - the hard timeouts are longer and meant to catch the case when code does not terminate at all, as opposed to being slow.
From my research, Java does not seem to have a non-deprecated provision for running non-cooperative code, which, in a way, is a gaping hole in the security model. Either I can run foreign code and control the permissions it has (SecurityManager), or I cannot run foreign code, because it might end up taking up a whole CPU with no non-deprecated means to stop it.
double x = 2.0;
while(true) {x = x*x}; // do not terminate
System.out.print(x); // prevent optimization
I can think of a not so great way to do this. If you can detect when it is taking too much time, you can have the method check for a boolean in every step. Have the program change the value of the boolean tooMuchTime to true if it is taking too much time (I can't help with this). Then use something like this:
Method(){
//task1
if (tooMuchTime == true) return;
//task2
if (tooMuchTime == true) return;
//task3
if (tooMuchTime == true) return;
//task4
if (tooMuchTime == true) return;
//task5
if (tooMuchTime == true) return;
//final task
}

Categories