栏目导航
热点推荐
- 三十条有用的 Java 编程规则
- Java制作水印图片源码
- Java常见异常及可能的导致原因
- Java中的修饰词使用方法总结
- J2EE系统异常的处理准则
- Java中的异常、断言、日志解析(
- Java面试技巧:Java面试题集锦(
- 面向Java开发人员的Scala指南:
- Java程序员:一刻钟精通正则表达
- 网友经验分享:学好java开发的关
- 专家解答:创建表格与数据库进行
- Java远程访问Domino数据库
阅览排行
使用实时Java降低Java应用程序的易变性(2)
www.jz123.cn 2010-10-22 来源: 中国建站 责任编辑(袁袁) 我要投递新闻
清单 7. 用于不断生成垃圾的 GCStressThread 类
class GCStressThread extends Thread { HashMap map; volatile boolean stop = false; class BinaryTree { public BinaryTree left; public BinaryTree right; public Long value; } private void allocateSomeData(boolean useSleep) { try { for (int i=0;i < 125;i++) { if (useSleep) Thread.sleep(100); BinaryTree newTree = createNewTree(15); // create full 15-level BinaryTree this.map.put(new Integer(i), newTree); } } catch (InterruptedException e) { stop = true; } } } public void initialize() { this.map = new HashMap(); allocateSomeData(false); System.out.println("\nFinished initializing\n"); } public void run() { while (!stop) { allocateSomeData(true); } } } |
GCStressThread 通过 HashMap 维护一组 BinaryTree。它为存储新 BinaryTree 结构的 HashMap 迭代一组相同的 Integer 键,这些结构是完全填充的 15 级 BinaryTrees。(所以每个 BinaryTree 有 215 = 32,768 个节点被存储在 HashMap 中)。HashMap 在每次迭代时都持有 125 个 BinaryTree(活动数据),它每隔 10 毫秒就会将其中一个节点替换为新的 BinaryTree。通过这种方式,此数据结构维持着一个相当复杂的活动对象集,并且以特定速率生成垃圾。首先使用 initialize() 例程,借助 125 个 BinaryTree 来初始化HashMap,initialize() 例程不会在对每棵树的收集之间暂停。一旦启动了 GCStressThread(在启动服务器之前),它将通过服务器的工作者线程全权处理 TaskHandler 操作。
我们不打算使用客户端来驱动此服务器。我们将直接在服务器的主循环(在 Server.start() 方法中)中创建 NUM_OPERATIONS == 10000 操作。清单 8 给出了 Server.start() 方法:
清单 8. 在服务器内部分派操作
public void start() { for (int m=0; m < NUM_OPERATIONS;m++) { TaskHandler task = new TaskHandler(); threadPool.execute(task); } try { while (!serverShutdown) { // boolean set to true when done Thread.sleep(1000); } } catch (InterruptedException e) { } } public void start() { while (true) { // main server handling loop, find a task to do // create a "TaskHandler" object to complete this operation TaskHandler task = new TaskHandler(); this.threadPool.execute(task); } this.threadPool.shutdown(); } public static void main(String[] args) { int serverThreads = Integer.parseInt(args[0]); Server theServer = new Server(serverThreads); theServer.start(); } } class TaskHandler extends Runnable { public void run() { // code to handle a "task" } } |
上一篇:使用实时Java降低Java应用程序的易变性(1) 下一篇:使用实时Java降低Java应用程序的易变性(3)