If the code faced a specific case I want to stop the current execution but continue the parent loop.
main() {
while(line not empty) {
// blablabla
method1()
// tadatadatada
}
}
method1() {
// blablabla
method2()
// etcetcetc
}
method2() {
// blablabla
if (var == 1)
stop the execution of the current method and parent method
// etcetcetc
}
In the case explained below, if var == 1, all etcetcetc part of code must not be executed, but tadatadatada must be...
So I want to stop all children executions.
Is there a solution to do that in Java?
Return a value from method2 and check it in method1. If it meets a condition, return from method1 too.
Something like:
method1() {
var shouldBreak = method2();
if (shouldBreak) {
return
}
// more stuff
}
Look into Java Multithreading. This will allow you to run multiple methods simultaneously and give you full control over when to stop a specific thread.
Here's a starting point from another: Threads in Java
I don't quite understand fully what you're asking as your example doesn't have extensive clarity, but hopefully this is what you're looking for.
Related
I have a requirement wherein I want to make sure that if a particular method "Repo.get()" is getting called from the class, it should get called inside a synchronized block (or a synchronized method). I can modify the "Repo.get()". But I cannot modify the calling classes.
Check the below example:
class A {
public void testA() {
Repo r = new Repo();
synchronized (this) {
r.get();
}
}
}
class B {
public void testB() {
Repo r = new Repo();
r.get();
}
}
class Repo {
public void get() {
// My code goes here.
// When called from A, we should be able to print "YES"
// When called from B, we should be able to print "NO"
}
}
How can we achieve this?
Thanks,
Nikhil
it should get called inside a synchronized block (or a synchronized method).
This is a non-sensical requirement. In that I can trivially adhere to it accomplishing absolutely not a thing.
synchronized (new Object()) {
// this does absolutely nothing
}
synchronized blocks do nothing except interact with other synchronized blocks on the same object reference. Thus, it makes no sense to demand that 'synchronized' is used. It can make sense to demand that 'synchronized on this specific X is used'.
The above code does nothing by definition because it synchronizes on an object that no other thread could possibly reference, thus guaranteeing it is completely useless, which then proves that your requirement is silly.
If you want to upgrade into the non-silly requirement ('must sync on specifically this object reference'):
Thread.holdsLock(objRef) is all you need.
If you want to check if the current thread is holding any lock, well, that's not really possible, but it's good that this isn't possible, because that'd be a silly thing to want to do.
I have the following 2 init methods that call doDataInit():
public void sessionBegin(SessionEvent event)
throws Exception {
....
doDataInit();
}
public void init() {
...
doDataInit();
}
and the method:
private Future<WorkItems>
doDataInit() {
//do some stuff
Callable<WorkItems> initData = getData();
Future<WorkItems> result = EXECUTOR.submit(initData);
return result;
}
Now what I want to do is have a check inside the doDataInit method, that if true is going to sleep the task execution. Or otherwise said - I want to block the execution of the task until a certain condition is met and periodically check if the given condition is met. Once it is - continue execution.
What is the best (most effective) way to achive that in this scenario?
What I can currently think of is:
sleep the thread - uneffective
somehow block the callable
block the Executor
have a for loop where I perform the checks s ceratain amount of times
Thanks in advance.
I have a requirement where i need to call multiple methods in a sequential manner. But if any one of the method fails due to a validation, the program should not continue. I cannot use "Throw Exception because these are not actually exception rather than a condition that satisfies my requirement and after satisfying it, I don't want the program to continue.
Below is a piece of code for example and understanding. Even i use Return, it still continues to next method.
public void method1(){
System.out.println("Method 1");
return;
}
public void method2(){
System.out.println("Method 2");
return;
}
public void method3(int a) throws Exception{
System.out.println("Method 3");
if (a==3) FinalMethod();
return;
}
public void method4(){
System.out.println("Method 4");
return;
}
public void method5(){
System.out.println("Method 5");
return;
}
public void FinalMethod() {
System.out.println("This is the final method - end of the program");
return;
}
public void callMethod() throws Exception{
method1();
method2();
method3(3);
method4();
method5();
}
The method callMethod will be called from Main method. Please help me to learn this.
Edited: If The argument is 3 in method3, it should call Finalmethod and after that the program should end. I dont want it to go for method4 and method5.
Why not have the methods return a boolean to determine if the next method should run?
This is what's currently going on in in the stack when you call FinalMethod from method3:
main -> callMethod -> method3 -> FinalMethod
So when FinalMethod finishes, you go back to method3, and from there, go back to callMethod, and continue running to the end.
What I would do is make method3 return a boolean if you want to exit and call it with regard to this:
public boolean method3(int a) {
System.out.println("Method e");
return a==3;
}
...
//In callMethod
if (method3(3)) { //If we want to exit after running method3
FinalMethod();
return;
}
Though you may use System.exit(exitCode), this is not good practice, as it violates the program flow - that the program will only end at the end of the main function.
Though method3 is currently throwing an exception, you don't actually throw one in the method. However, exceptions should only be used for undefined behaviour (particularly relating to circumstances beyond your control, eg. external code). It is preferable to provide a user-friendly error and continue the program if possible, or exit gracefully if not.
Unrelated tips:
You do not have to call return at the end of a void function.
By default, you should make methods private, and only make them public when required
Calling return at the end of a method block is redundant in this scenario.
Assuming that you are looking to terminate the program on error, you can possibly use System.exit(-1) in your catch (if you follow this way), or in the if statement, if this is how you are checking for the error
Edit: I should also clarify that there is no specific meaning to using System.exit(-1) as opposed to using any System.exit(n) where n != 0, unless otherwise specified in your own documentation
I have looked in the Javadoc but couldn't find information related to this.
I want the application to stop executing a method if code in that method tells it to do so.
If that sentence was confusing, here's what I want to do in my code:
public void onClick(){
if(condition == true){
stopMethod(); //madeup code
}
string.setText("This string should not change if condition = true");
}
So if the boolean condition is true, the method onClick has to stop executing further code.
This is just an example. There are other ways for me to do what I am trying to accomplish in my application, but if this is possible, it would definitely help.
Just do:
public void onClick() {
if(condition == true) {
return;
}
string.setText("This string should not change if condition = true");
}
It's redundant to write if(condition == true), just write if(condition) (This way, for example, you'll not write = by mistake).
return to come out of the method execution, break to come out of a loop execution and continue to skip the rest of the current loop. In your case, just return, but if you are in a for loop, for example, do break to stop the loop or continue to skip to next step in the loop
To stop executing java code just use this command:
System.exit(1);
After this command java stops immediately!
for example:
int i = 5;
if (i == 5) {
System.out.println("All is fine...java programm executes without problem");
} else {
System.out.println("ERROR occured :::: java programm has stopped!!!");
System.exit(1);
}
There are two way to stop current method/process :
Throwing Exception.
returnning the value even if it is void method.
Option : you can also kill the current thread to stop it.
For example :
public void onClick(){
if(condition == true){
return;
<or>
throw new YourException();
}
string.setText("This string should not change if condition = true");
}
You can just use return to end the method's execution
Either return; from the method early, or throw an exception.
There is no other way to prevent further code from being executed short of exiting the process completely.
I think just using return; would do the job
I have a program which can be defined as something like this
reset() {
//sets all variables to initial values
//clears all arrays
method1();
}
method1 (){
//doSomeStuff;
method2();
}
method2(){
//doStuff
method3();
}
method3(){
//doStuff
if (jobDone) reset(); //here the cycle closes
else method2();
}
All these methods are quite calculations heavy.
Depending on the input data and the result the program may do just a couple of cycles and throw a 'stack overflow' error.
I have changed the VM flag -Xss (-Xss8M) but this doesn't really solve the problem.
Is there any way to make it working almost infinitely?
Solution previously mentioned by Luiggi Mendoza: How to avoid stack overflow error
When you call reset, it calls method1, it calls method2, it calls method3 and it calls either reset or method2 both causing infinite cycle in recursion.
You probably want:
if (jobDone) return; // here the cycle realy closes
instead of
if (jobDone) reset(); //here the do _not_ close
In case you realy want infinite cycling of your code this will not cause SO due to method calling of reset or methodi:
// assuming jobDone is actually a method, you might need this variable
boolean startReset = true;
while (true) {
if (startReset) {
//sets all variables to initial values
//clears all arrays
//doSomeStuff from method1;
}
//doStuff from method2
//doStuff
startReset = jobDone;
}
}