2016-12-21 50 views
0

获得价值时,一些重构之后,我们突然看到这种情况出现在运行时:斯卡拉的StackOverflowError从地图

java.lang.StackOverflowError: null 
at scala.collection.MapLike$MappedValues.get(MapLike.scala:249) 
at scala.collection.MapLike$MappedValues.get(MapLike.scala:249) 
at scala.collection.MapLike$MappedValues.get(MapLike.scala:249) 
at scala.collection.MapLike$MappedValues.get(MapLike.scala:249) 
at scala.collection.MapLike$MappedValues.get(MapLike.scala:249) 

我们发现了类似的问题,但他们都没有的正是这种痕迹:

回答

3

上述问题指向MapLike.mapValues的懒惰,经过一些进一步的研究,我们找到了原因。

我们有一些清理代码,定期打电话,做这样的事情:

case class EvictableValue(value: String, evictionTime: Instant) 

    val startData = Map(
    "node1" -> Map(
     "test" -> EvictableValue("bar", Instant.now().plusSeconds(1000)) 
    ) 
) 

    // every n seconds we do the below code 
    // here simulated by the fold 
    val newData = (1 to 20000).foldLeft(startData){(data, _) => 
    data.mapValues { value => 
     value.filter(_._2.evictionTime.isBefore(Instant.now())) 
    } 
    } 

    // this stack overflows 
    val result = newData.get("test") 

的解决方案是切换到Map.transform

data.transform { (_, value) => 
    value.filter(_._2.evictionTime.isBefore(Instant.now())) 
} 

或迫使视图解释here

data.mapValues{ value => 
    value.filter(_._2.evictionTime.isBefore(Instant.now())) 
}.view.force