0

I have a for loop which runs based on value of boolean variable.

public class LoopClass{
..
private boolean[] toInterrupt = new boolean[];
public boolean getValue() {
        
        return toInterrupt[0];
    }

    public void setValue(boolean newValue) {
        toInterrupt[0] = newValue;
    }
}
public method abc{

for loop{

if (getValue()){
   break:
}}}

I want to interrupt this loop through servlet:

public class interruptServlet exetnds HttpServlet {

LoopClass = lp = new LoopClass();
lp.setValue(true)
}

Even after executing servlet, boolean toInterrupt[0] always remain false. How can i change boolean value through servlet to stop the loop ?

4
  • 1
    If interruptServlet is running in another thread (as I assume it is), you need to properly manage the multi-threaded access to the variable to avoid data consistency issues. BTW, please, post the code as close as possible to what you're actually doing, so volunteers can help you better; the one you posted doesn't compile. Commented Sep 29, 2023 at 7:28
  • 3
    If you create a new instance of LoopClass, it won’t affect the value in some other existing instance. Commented Sep 29, 2023 at 7:36
  • @TimMoore: Thanks for your comment. how can i change the value in existing instance ? Commented Sep 29, 2023 at 7:51
  • 1
    You need a reference to that instance. I think the question would benefit from a lot more context about what your use case is overall. Commented Sep 29, 2023 at 8:05

1 Answer 1

1

As said before, the new LoopClass instance does not share any state with the actual servlet.

There is a pretty easy way to share state between servlets: the ServletContext. For instance:

LoopClass:

private static final String INTERRUPTED_ATTRIBUTE = LoopClass.class.getName() + ".interrupted";

public static void setInterrupt(ServletContext context, boolean interrupt) {
    context.setAttribute(INTERRUPTED_ATTRIBUTE, interrupt);
}

private boolean interrupted() {
    return Boolean.TRUE.equals(getServletContext().getAttribute(INTERRUPTED_ATTRIBUTE);
}

InterruptServlet:

LoopClass.setInterrupt(getServletContext(), true);

Note that I kept all of the actual code for interrupting in LoopClass. That way you can easily rename the attribute name without having to change other code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.