Equivalent of scala.concurrent.util.Unsafe in Scala 2.12

132 Views Asked by At

I have created empty instance of my object and then initialise it using run time values. Implementation was based on scala.concurrent.util.Unsafe in Scala 2.11 and it worked fine.

I understand Unsafe is bad and hence has been deprecated in Scala 2.12.

If it's deprecated then what's equivalent of Unsafe in Scala 2.12?

1

There are 1 best solutions below

0
On BEST ANSWER

Assuming you're running on a JVM where sun.misc.Unsafe is still available (this will limit which JVMs you can run on, but so did using scala.concurrent.util.Unsafe so no immediate loss):

val unsafeInstance = // use in place of Scala 2.11 usages of scala.concurrent.util.Unsafe.instance
  classOf[sun.misc.Unsafe]
    .getDeclaredFields
    .filter(_.getType == classOf[sun.misc.Unsafe])
    .headOption
    .map { field => 
      field.setAccessible(true)
      field.get(null).asInstanceOf[sun.misc.Unsafe]
    }
    .getOrElse { throw new IllegalStateException("Can't find instance of sun.misc.Unsafe") }

Code is very slightly adapted from the Scala 2.11 source.

It's possible that this is an instance of spending so much time thinking about "could" that one didn't think about "should".