什么会使一个线程挂起Java中的错误类型转换?

时间:2017-11-20 20:50:30

标签: java multithreading jvm

我最近碰巧在Java中进行了不正确的类型转换 - 将Double转换为long。 此类型转换代码是作为单独线程运行的逻辑的一部分(使用ExectorService的singleThread)。该线程每30秒无限运行一次。它有一个无限循环,每30秒运行一次。

当我执行此代码时,我的Java代码挂起了类型转换(从Double转换为long),而不是抛出运行时错误。

所以,我想知道什么会导致JVM挂起错误的类型转换?

P.S:我会尝试粘贴我的实际代码。

更新

下面是我的单线程executorService执行的代码。

void collectMetrics() {
     // Create the connection
     while(RETRY){ // Default RETRY is True 
         Long currTime = System.currentTimeMillis();
         Socket connection = createConnection();

         if (connection == null){
             waitForSometime();
             continue;
         }
         // Get the output stream
         DataOutputStream outputStream = getDataOutputStream(connection);

         if (outputStream == null){
             waitForSometime();
             continue;
         }
         // Get metrics from JMX
         Map<String, Gauge> g = metricRegistry.getGauges();
         for(Entry<String, Gauge> e : g.entrySet()){
             String metricName = convertToMetricStandard(e.getKey());
             Long metricValue = (Long) e.getValue().getValue(); // CODE HUNGS HERE INDEFINITELY. 

             String metricToSend = String.format("%s %s %s\n", metricName, metricValue, currTime);
             LOGGER.debug("Metric to send - `{}`", metricToSend); // TODO: Remove
             try {
                 outputStream.writeBytes(metricToSend);
                 outputStream.flush();
                 // Remove the metric from JMX after successfully sending metric to graphite
                 removeMetricFromJMX(metricName);
             } catch (IOException e1) {
                 LOGGER.error("Unable to send metric to Graphite - ", e1.getMessage());
             }

         }

         closeOutputStream();
         closeConnection();

         waitForSometime();
     }
 }

所以,基本上我的程序无限期地挂起了不正确的转换 - Long metricValue = (Long) e.getValue().getValue();e.getValue().getValue()此处返回double值,但在此我转换为Long而不是String

以上代码的作用是什么?

  • 它从JMX收集指标数据并将其发送到石墨。 (默认等待时间为30秒。)

0 个答案:

没有答案