Skip to content

Commit f2d0231

Browse files
committed
SI-9095 Memory leak in LinkedHasMap and LinkedHashSet
The clear() method in scala.collection.mutable.LinkedHashSet and scala.collection.mutable.LinkedHashMap does not set lastEntry to null. In result it holds a reference to an object that was removed from the collection.
1 parent 5d7098c commit f2d0231

File tree

4 files changed

+52
-0
lines changed

4 files changed

+52
-0
lines changed

src/library/scala/collection/mutable/LinkedHashMap.scala

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,7 @@ class LinkedHashMap[A, B] extends AbstractMap[A, B]
160160
override def clear() {
161161
clearTable()
162162
firstEntry = null
163+
lastEntry = null
163164
}
164165

165166
private def writeObject(out: java.io.ObjectOutputStream) {

src/library/scala/collection/mutable/LinkedHashSet.scala

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ class LinkedHashSet[A] extends AbstractSet[A]
112112
override def clear() {
113113
clearTable()
114114
firstEntry = null
115+
lastEntry = null
115116
}
116117

117118
private def writeObject(out: java.io.ObjectOutputStream) {
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package scala.collection.mutable
2+
3+
import org.junit.runner.RunWith
4+
import org.junit.runners.JUnit4
5+
import org.junit.{ Assert, Test }
6+
7+
import scala.collection.mutable
8+
9+
/* Test for SI-9095 */
10+
@RunWith(classOf[JUnit4])
11+
class LinkedHashMapTest {
12+
class TestClass extends mutable.LinkedHashMap[String, Int] {
13+
def lastItemRef = lastEntry
14+
}
15+
16+
@Test
17+
def testClear: Unit = {
18+
val lhm = new TestClass
19+
Seq("a" -> 8, "b" -> 9).foreach(kv => lhm.put(kv._1, kv._2))
20+
21+
Assert.assertNotNull(lhm.lastItemRef)
22+
lhm.clear()
23+
Assert.assertNull(lhm.lastItemRef)
24+
}
25+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package scala.collection.mutable
2+
3+
import org.junit.runner.RunWith
4+
import org.junit.runners.JUnit4
5+
import org.junit.{ Assert, Test }
6+
7+
import scala.collection.mutable
8+
9+
/* Test for SI-9095 */
10+
@RunWith(classOf[JUnit4])
11+
class LinkedHashSetTest {
12+
class TestClass extends mutable.LinkedHashSet[String] {
13+
def lastItemRef = lastEntry
14+
}
15+
16+
@Test
17+
def testClear: Unit = {
18+
val lhs = new TestClass
19+
Seq("a", "b").foreach(k => lhs.add(k))
20+
21+
Assert.assertNotNull(lhs.lastItemRef)
22+
lhs.clear()
23+
Assert.assertNull(lhs.lastItemRef)
24+
}
25+
}

0 commit comments

Comments
 (0)