Search code examples
javamultithreadingparallel-processingdatabase-triggerthread-sleep

java - Pausing all running threads for some time


For instance consider the below scenario.

App1: I have a multiple-threaded java app, which enters a lot of files in DB.

App2: when i access the DB using some other app, its slow in fetching results.

So when both apps work simultaneously, it takes great time for DB fetching results on the front-end app2.

Here, i want to pause all transactions(threads) on App1 for some 'x min' time. Considering a trigger has already been installed when app 2 is being used. So when App2 is idle, App1 will resume as if nothing happened. Please list some or one best approach to achieve this

Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
    for (Map.Entry<Thread, StackTraceElement[]> entry : threads.entrySet()) {
        entry.getKey().sleep();
    }

This didn't worked well.


Solution

  • Just to try:

    private List<PausableThread> threads = new ArrayList<PausableThread>();
    
    private void pauseAllThreads()
    {
        for(PausableThread thread : this.threads)
        {
            thread.pause();
        }
    }
    

    And your Thread class will be something like this:

    public class MyThread extends Thread implements PausableThread
    {
    
    private boolean isPaused = false;
    
    @Override
    public void pause()
    {
        this.isPaused = true;
    }
    
    @Override
    public void run()
    {
        while(!Thread.currentThread().isInterrupted())
        {
            // Do your work...
    
            // Check if paused
            if(this.isPaused)
            {
                try
                {
                    Thread.sleep(10 * 1000);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
    }
    

    And the PausableThread interface:

    public interface PausableThread
    {
        void pause();
    }