Unloading rJava and/or restarting JVM

可紊 提交于 2019-12-04 18:41:51

问题


I would like to use rJava in combination with mcparallel but obviously the JVM cannot be forked. Therefore a separate JVM instance needs to be initiated for each child process, e.g:

library(rJava)
library(parallel)
myfile <-  system.file("tests", "test_import.xlsx", package = "xlsx")

#This works:
mccollect(mcparallel({
  #Automatically initiates JVM in child
  xlsx::read.xlsx(myfile, 1)
}))

However the problem in my case is that the JVM has already been initiated in the (main) parent process as well. This makes it impossible to use rJava in the child process:

#init JVM in parent
.jinit()

#Doesn't work anymore
mccollect(mcparallel({
  xlsx::read.xlsx(myfile, 1)
}))

So what I really need is a way to shutdown/kill and restart the JVM in the child process. Simply detach("package:rJava", unload = TRUE) doesn't seem to do the trick. The force.init parameter doesn't seem to result in a restart either:

#Also doesn't work:
.jinit()
mccollect(mcparallel({
  .jinit(force.init = TRUE)
  xlsx::read.xlsx(myfile, 1)
}))

Is there some way I can forcefully shutdown/kill the JVM in order to reinitiate it in the child process?


回答1:


There is a way to run expressions using rJava in parallel based on running the parallel processes to get and assemble all results BEFORE you load the rJava library in the main process. As the main R process has not initiated jvm then java is started in each single subprocess and this particular instance will die together with subprocess as well.

# Rsession started
library(parallel)
myfile <-  system.file("tests", "test_import.xlsx", package = "xlsx")
e <- expression({
require(rJava)
require(xlsx)
read.xlsx(myfile, 1)
})
p <- mcparallel(e)
q <- mcparallel(e)
pq <- mccollect(list(p, q))

# again to check reproducibility
p <- mcparallel(e)
q <- mcparallel(e)
pq2 <- mccollect(list(p, q))
identical(unname(pq),unname(pq2))

# see the result if it is the right content and not tryerr
pq

# now the main continues ...
# and if necessary even load rJava


来源:https://stackoverflow.com/questions/24337383/unloading-rjava-and-or-restarting-jvm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!