When does .getThreadCpuTime return nil?

124 views
Skip to first unread message

lawrence...@gmail.com

unread,
Sep 22, 2017, 4:37:04 PM9/22/17
to Clojure
I've been using this code for years. I copy and pasted it from someone else on this group, someone much smarter than I am. I have never seen an error from this code. Now suddenly I get a null pointer exception at the last line of this code: 

(ns denormalize_mysql_to_mongodb.monitoring
  (:import
   java.lang.management.ManagementFactory)
  (:require [clojure.string :as st]))


(defn thread-top
  "Return a seq of threads sorted by their total userland CPU usage."
  []
  (let [mgr (ManagementFactory/getThreadMXBean)
        cpu-times (map (fn [t]
                         [(.getThreadCpuTime mgr (.getId t)) t])
                    (threads))]
    (map
      (fn [[cpu t]] [cpu (.getName t) (.getId t) t])
      (reverse (sort-by first cpu-times)))))

This error is thrown at startup. I don't know much about ThreadMXBean. Can anyone give me a clue why any of this would be nil? 





Neil Okamoto

unread,
Sep 22, 2017, 7:34:49 PM9/22/17
to Clojure

Maybe it's because you attempted method invocation via reflection but the object is nil. So for example if (threads) returns a list containing nils, then calling (.getId t) or (.getName t) would probably throw a null pointer exception. I'm not sure it's possible for (ManagementFactory/getThreadMXBean) to return nil, but if it does then (.getThreadCpuTime mgr ...) would similarly fail.

So best guess is, take a look at the implementation of "threads".

lawrence...@gmail.com

unread,
Sep 23, 2017, 11:03:34 PM9/23/17
to Clojure

Thanks for the answer. I am surprised because I used this code for years without ever seeing that error. I'm trying to imagine what I did differently this one time. I've added error detection, we'll see if it happens again. 

Neil Okamoto

unread,
Sep 24, 2017, 9:33:26 PM9/24/17
to clo...@googlegroups.com
Ok, hope it works out. 
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clo...@googlegroups.com
Note that posts from new members are moderated - please be patient with your first post.
To unsubscribe from this group, send email to
clojure+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to a topic in the Google Groups "Clojure" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/clojure/isBN8-E59qo/unsubscribe.
To unsubscribe from this group and all its topics, send an email to clojure+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages