Showing posts with label stop. Show all posts
Showing posts with label stop. Show all posts

Saturday, 9 May 2020

docker kill vs docker stop

Both the commands 'docker kill' and 'docker stop' are used to stop the container.

'docker kill' command sends 'SIGKILL' signal to the container, whereas 'docker stop' sends 'SIGTERM' signal, after a grace period it sends SIGKILL signal.

SIGTERM vs SIGKILL
a. 'SIGTERM' command tries the kill the process in a polite way, whereas SIGKILL command kill the process in a harsh way.

b. 'SIGTERM' command internally executes the command 'kill', whereas 'SIGKILL' command internally executes 'kill -9'

c. SIGTERM command can be handled, but SIGKILL can't be handled.


Previous                                                    Next                                                    Home

Sunday, 12 January 2020

How to specify timeout to a thread?


There can be multiple ways to stop a thread after certain time period. I choose below approach.

Just interrupt the thread, when thread reaches to specified time.


Step 1: Create TimerTask that interrupts the thread after given time.

TimeoutTask.java
package com.sample.app;

import java.util.TimerTask;

public class TimeoutTask extends TimerTask {
 Thread thread;

 TimeoutTask(Thread thread) {
  this.thread = thread;
 }

 public void run() {
  if (thread != null && thread.isAlive()) {
   thread.interrupt();
  }
 }

}

Step 2: Create runnable task that schedules the timer task before starting execution.


MyTask.java
package com.sample.app;

import java.util.Timer;
import java.util.concurrent.TimeUnit;

public class MyTask implements Runnable {
 private long timeoutInSeconds;
 Timer timer;

 MyTask(long timeoutInSeconds) {
  this.timeoutInSeconds = timeoutInSeconds;
  timer = new Timer(true);
 }

 @Override
 public void run() {
  timer.schedule(new TimeoutTask(Thread.currentThread()), timeoutInSeconds * 1000);
  int count = 0;
  while (true) {
   count++;
   try {
    TimeUnit.SECONDS.sleep(1);
    System.out.println("Executed for " + count + " seconds");
   } catch (InterruptedException e) {
    System.out.println("Task interrupted");
    break;
   }
  }
 }

}


App.java
package com.sample.app;

public class App {

 public static void main(String args[]) {
  // Set the time out for task
  MyTask task = new MyTask(5);
  Thread thread = new Thread(task);

  thread.start();

 }

}


Run App.java, you will see below messages in console.
Executed for 1 seconds
Executed for 2 seconds
Executed for 3 seconds
Executed for 4 seconds
Task interrupted


You may like