当前位置:网站首页 > Java教程 > 正文

java函数停服教程



 1 import java.util.concurrent.ScheduledThreadPoolExecutor;  2 import java.util.concurrent.TimeUnit;  3  4 /  5  * 体验 Java 优雅停服  6  *  7  * @author 一猿小讲  8 */  9 public class Application { 10 11 / 12  * 监控服务 13 */ 14 private ScheduledThreadPoolExecutor monitorService; 15 16 public Application() { 17 monitorService = new ScheduledThreadPoolExecutor(1); 18  } 19 20 / 21  * 启动监控服务,监控一下内存信息 22 */ 23 public void start() { 24 System.out.println(String.format("启动监控服务 %s", Thread.currentThread().getId())); 25 monitorService.scheduleWithFixedDelay(new Runnable() { 26  @Override 27 public void run() { 28 System.out.println(String.format("最大内存: %dm 已分配内存: %dm 已分配内存中的剩余空间: %dm 最大可用内存: %dm", 29 Runtime.getRuntime().maxMemory() / 1024 / 1024, 30 Runtime.getRuntime().totalMemory() / 1024 / 1024, 31 Runtime.getRuntime().freeMemory() / 1024 / 1024, 32 (Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory() + 33 Runtime.getRuntime().freeMemory()) / 1024 / 1024)); 34  } 35 }, 2, 2, TimeUnit.SECONDS); 36  } 37 38 / 39  * 释放资源(代码来源于 flume 源码) 40  * 主要用于关闭线程池(看不懂的同学莫纠结,当做黑盒去对待) 41 */ 42 public void stop() { 43 System.out.println(String.format("开始关闭线程池 %s", Thread.currentThread().getId())); 44 if (monitorService != null) { 45  monitorService.shutdown(); 46 try { 47 monitorService.awaitTermination(10, TimeUnit.SECONDS); 48 } catch (InterruptedException e) { 49 System.err.println("Interrupted while waiting for monitor service to stop"); 50  } 51 if (!monitorService.isTerminated()) { 52  monitorService.shutdownNow(); 53 try { 54 while (!monitorService.isTerminated()) { 55 monitorService.awaitTermination(10, TimeUnit.SECONDS); 56  } 57 } catch (InterruptedException e) { 58 System.err.println("Interrupted while waiting for monitor service to stop"); 59  } 60  } 61  } 62 System.out.println(String.format("线程池关闭完成 %s", Thread.currentThread().getId())); 63  } 64 65 / 66  * 应用入口 67 */ 68 public static void main(String[] args) { 69 Application application = new Application(); 70 // 启动服务(每隔一段时间监控输出一下内存信息) 71  application.start(); 72 73 // 添加钩子,实现优雅停服(主要验证钩子的作用) 74 final Application appReference = application; 75 Runtime.getRuntime().addShutdownHook(new Thread("shutdown-hook") { 76  @Override 77 public void run() { 78 System.out.println("接收到退出的讯号,开始打扫战场,释放资源,完成优雅停服"); 79  appReference.stop(); 80  } 81  }); 82 System.out.println("服务启动完成"); 83  } 84 }

版权声明


相关文章:

  • java web idea 视频教程2024-12-13 09:42:01
  • java笔记使用教程2024-12-13 09:42:01
  • java教程谁的好2024-12-13 09:42:01
  • java教程哪个2024-12-13 09:42:01
  • java苹果安装教程2024-12-13 09:42:01
  • java视频教程 网盘2024-12-13 09:42:01
  • java 离线教程2024-12-13 09:42:01
  • java知识入门教程2024-12-13 09:42:01
  • java游戏实战教程2024-12-13 09:42:01
  • java实际应用教程2024-12-13 09:42:01