【问题标题】:Serializing a tree map of JMS messages per minute每分钟序列化 JMS 消息的树形图
【发布时间】:2012-04-04 20:53:41
【问题描述】:

我试图将在一分钟内收到的 Message 类的所有 JMS 对象存储到树形图中,并将其精确时间作为键。完成一分钟后,我希望序列化映射并将 byte[] 返回到另一个班级。同时,我创建了一个新的树形图来存储下一组 JMS 消息一分钟。

public class StoreMessage {

    private static long start_nanotime = System.nanoTime();
    private static Thread thisThread = Thread.currentThread();
    private static int timeToRun = 60000; // 1 minute
    private static byte[] b = null;
    public static Map<Long, Message> map1 = new TreeMap<Long, Message>();

    public static byte[] store(Message message) {

        new Thread(new Runnable() {

            public void run() {
                try {
                    sleep(timeToRun);
                    thisThread.interrupt();
                    b = serializer.serialize(map1);
                    new TreeMap<Long, Message>();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        while (!Thread.interrupted()) {
            long precise_time = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()) + (System.nanoTime()
                    - start_nanotime);
            map1.put(precise_time, message);

        }
        return b;
    }
}

这段代码有些不工作。为什么?它给了我 java.lang.OutOfMemoryError: Java heap space 的错误我还注意到它一直只向地图写入一条消息,即如果消息是“hi”,那么祝你好运“——这是两条 jms 消息; StoreMessage 类一次接收一条消息..即它首先会收到“hi”,一旦处理了这条消息,它就会检索下一条消息。但我注意到,整整一分钟,当线程没有被中断时,它只将第一条消息写入地图并给出错误。我该如何解决这些问题?

【问题讨论】:

    标签: java multithreading jms treemap


    【解决方案1】:

    问题是您的 ma​​p1 从未真正重置,因为缺少分配。

       public void run() {
                    try {
                        sleep(timeToRun);
                        thisThread.interrupt();
                        b = serializer.serialize(map1);
                        map1 = new TreeMap<Long, Message>();  // Changed this line
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
    

    当然,你也可以简单地清除地图:

    map1.clear();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-25
      • 2012-09-13
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      • 2021-05-14
      • 2011-06-14
      • 1970-01-01
      相关资源
      最近更新 更多