2016-12-21 48 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