Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7957165
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T04:12:30+00:00 2026-06-04T04:12:30+00:00

Is it possible to rewrite this code for better working with processor? I have

  • 0

Is it possible to rewrite this code for better working with processor?
I have a class, which does some tasks with fixed periodicy in a separate thread. Sometimes this process can be paused and resumed. Currently I am using a flag for pausing, it works fine, but loop in this way still loads processor when process is paused. Is it possible to fix this?

private boolean mIsCanceled = false;
private boolean mIsPaused = true; // TODO more efficient for processor way of pausing is required
private final Thread mTimerThread = new Thread(new Runnable() {
    @Override
    public void run() {
        while(!mIsCanceled){
            try {
                Thread.sleep(UPDATE_PERIOD);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (!mIsPaused){
                doStep();
            }
        }
    }
});

public MyClass(){
    mTimerThread.start();
}

private void pause(){
    mIsPaused = true;
}

private void resume(){
    mIsPaused = false;
}

private void doStep(){
    // Some code
}

Please just provide alternative implementation of my code.

P.S. The environment is Android OS 2.2+

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T04:12:31+00:00Added an answer on June 4, 2026 at 4:12 am

    The tools available are:

    wait/notify – we are all trying to get away from this archaic system.

    Semaphores – once your thread has grabbed it you hold it until release so grabbing it again does not block. This means you cannot pause from within your own thread.

    CyclicBarrier – Must be created anew each time it is used.

    ReadWriteLock – My favorite. You can have as many threads pausing you as you like and you will only resume when all of them have called resume. You can even pause yourself if you wish.

    import java.util.concurrent.locks.ReadWriteLock;
    import java.util.concurrent.locks.ReentrantReadWriteLock;
    
    /**
     * PauseableThread is a Thread with pause/resume and cancel methods.
     *
     * The meat of the process must implement `step`.
     *
     * You can either extend this and implement `step` or use the factory.
     *
     * Note that I cannot extend Thread because my resume will clash with Thread's deprecated one. 
     *
     * Usage: Either write a `Stepper` and run it in a `PausableThread` or extend `PausableThread` and call `blockIfPaused()` at appropriate points.
     */
    public abstract class PauseableThread implements Runnable {
      // The lock.
      // We'll hold a read lock on it to pause the thread.
      // The thread will momentarily grab a write lock on it to pause.
      // This way you can have multiple pausers using normal locks.
      private final ReadWriteLock pause = new ReentrantReadWriteLock();
      // Flag to cancel the wholeprocess.
      private volatile boolean cancelled = false;
      // The exception that caused it to finish.
      private Exception thrown = null;
    
      @Override
      // The core run mechanism.
      public void run() {
        try {
          while (!cancelled) {
            // Block here if we're paused.
            blockIfPaused();
            // Do my work.
            step();
          }
        } catch (Exception ex) {
          // Just fall out when exception is thrown.
          thrown = ex;
        }
      }
    
      // Block if pause has been called without a matching resume.
      private void blockIfPaused() throws InterruptedException {
        try {
          // Grab a write lock. Will block if a read lock has been taken.
          pause.writeLock().lockInterruptibly();
        } finally {
          // Release the lock immediately to avoid blocking when pause is called.
          pause.writeLock().unlock();
        }
    
      }
    
      // Pause the work. NB: MUST be balanced by a resume.
      public void pause() {
        // We can wait for a lock here.
        pause.readLock().lock();
      }
    
      // Resume the work. NB: MUST be balanced by a pause.
      public void resume() {
        // Release the lock.
        pause.readLock().unlock();
      }
    
      // Stop.
      public void cancel() {
        // Stop everything.
        cancelled = true;
      }
    
      // start - like a thread.
      public void start() {
        // Wrap it in a thread.
        new Thread(this).start();
      }
    
      // Get the exceptuion that was thrown to stop the thread or null if the thread was cancelled.
      public Exception getThrown() {
        return thrown;
      }
    
      // Create this method to do stuff. 
      // Calls to this method will stop when pause is called.
      // Any thrown exception stops the whole process.
      public abstract void step() throws Exception;
    
      // Factory to wrap a Stepper in a PauseableThread
      public static PauseableThread make(Stepper stepper) {
        StepperThread pauseableStepper = new StepperThread(stepper);
        // That's the thread they can pause/resume.
        return pauseableStepper;
      }
    
      // One of these must be used.
      public interface Stepper {
        // A Stepper has a step method.
        // Any exception thrown causes the enclosing thread to stop.
        public void step() throws Exception;
      }
    
      // Holder for a Stepper.
      private static class StepperThread extends PauseableThread {
        private final Stepper stepper;
    
        StepperThread(Stepper stepper) {
          this.stepper = stepper;
        }
    
        @Override
        public void step() throws Exception {
          stepper.step();
        }
      }
    
      // My test counter.
      static int n = 0;
    
      // Test/demo.
      public static void main(String[] args) throws InterruptedException {
    
        try {
          // Simple stepper that just increments n.
          Stepper s = new Stepper() {
            @Override
            public void step() throws Exception {
              n += 1;
              Thread.sleep(10);
            }
          };
          PauseableThread t = PauseableThread.make(s);
          // Start it up.
          t.start();
          Thread.sleep(1000);
          t.pause();
          System.out.println("Paused: " + n);
          Thread.sleep(1000);
          System.out.println("Resuminng: " + n);
          t.resume();
          Thread.sleep(1000);
          t.cancel();
        } catch (Exception e) {
        }
      }
    }
    

    Edit: Code modified to be of more general use.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Lets say I have the following code: public class Base { // Some stuff
I have some delphi code which, given a list of items, calculates the total
Is it possible to rewrite this C# code into java? public interface IEnumerable<out T>
So, I am trying to make: sub.example.com/page rewrite to www.example.com/sub/page I have this code
I will be as specific as possible.. I have this code: // bintodec.cpp :
ok I have this code, that I'm studying class scope{ function printme(){ return hello;
Is it possible to re-write (Apache Mod-Rewrite) a URL from this: http://www.example.com/view.php?t=h5k6 to this
This is the code (now is full): HTML: <div id=content contentEditable=true onkeyup=highlight(this)>This is some
I have this .htaccess code that works perfectly: <IfModule mod_rewrite.c> RewriteEngine on RewriteRule !\.(js|ico|txt|gif|jpg|png|css)$
This might not be possible but before I rewrite part of my application I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.