Sahand
Sahand

Reputation: 8370

How to allocate less memory to Scala with IntelliJ

I'm trying to crash my program (run in IntelliJ) with an OutOfMemoryException:

  def OOMCrasher(acc: String): String = {
    OOMCrasher(acc + "ADSJKFAKLWJEFLASDAFSDFASDFASERASDFASEASDFASDFASERESFDHFDYJDHJSDGFAERARDSHFDGJGHYTDJKXJCV")
  }
  OOMCrasher("")

However, it just runs for a very long time. My suspicions is that it simply takes a very long time to fill up all the gigabytes of memory allocated to the JVM with a string. So I'm looking at how to make IntelliJ allocate less memory to the JVM. Here's what I've tried:

In Run Configurations -> VM options:

 --scala.driver.memory 1k || --driver.memory 1k

Both of these cause crashes with:

Unrecognized option: --scala.driver.memory
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

I've also tried to put the options in the Edit Configurations -> Program Arguments. This causes the program to run for a very long time again, not yielding an OutOfMemoryException.

EDIT:

I will accept any answer that successfully explains how to allocate less memory to the program, since that is the main question.

UPDATE:

Changing the function to:

  def OOMCrasher(acc: HisList[String]): HisList[String] = {
    OOMCrasher(acc.add("Hi again!"))
  }
  OOMCrasher(Cons("Hi again!", Empty))

where HisList is a simple LinkedList implementation as well as running with -Xmx3m caused the wanted exception.

Upvotes: 1

Views: 121

Answers (1)

Markus Appel
Markus Appel

Reputation: 3238

To functionally reach an OutOfMemoryException is harder than it looks, because recursive functions almost always run first into a StackOverflowException.

But there is a mutable approach that will guarantee an OutOfMemoryException: Doubling a List over and over again. Scala's Lists are not limited by the maximum array size and thus can expand until there is just no more memory left.

Here's an example:

def explodeList[A](list: List[A]): Unit = {
  var mlist = list

  while(true) {
    mlist = mlist ++ mlist
  }
}

To answer your actual question, try to fiddle with the JVM option -Xmx___m (e.g. -Xmx256m). This defines the maximum heap size the JVM is allowed to allocate.

Upvotes: 2

Related Questions