multithreading - java.lang.OutOfMemory Exception with Multithreaded Image Generate -
i trying copy lot of images java imageio
. each copy resizes original picture. size of image set huge (60,000). try use multi thread solve problem. here code:
package generate.image import scala.util.random._ import scala.math._ import java.io.file import java.io.printwriter import java.util.concurrent.{executorservice, timeunit, executors} import java.awt.image import java.awt.image.bufferedimage import javax.imageio.imageio class imageresizer{ def resizeimage(srcimgpath: string, distimgpath: string, width: int, height: int){ val srcfile: file = new file(srcimgpath) val srcimg: image = imageio.read(srcfile) val buffimg: bufferedimage = new bufferedimage(width, height, bufferedimage.type_int_rgb) buffimg.getgraphics().drawimage( srcimg.getscaledinstance(width, height, image.scale_smooth), 0, 0, null ) imageio.write(buffimg, "jpeg", new file(distimgpath)) } } class imageworker(imgsrc: string, imgname: string, width: int, height: int) extends runnable{ override def run(): unit = { val resizer = new imageresizer() resizer.resizeimage(imgsrc, imgname, width, height); } } object imagegenerate { def main(args:array[string]): unit = { // parameters val dirname = args(0) val images = new file(dirname).listfiles.filter(_.getname.endswith(".jpeg")) val imgcnt = images.length // threadpool val pool = executors.newfixedthreadpool(25) // copy norm for(i <- 0 until imgcnt){ for(cnt <- 1 20){ val width = nextint(200) + 300 val height = nextint(200) + 300 val imgsrc: string = images(i).getabsolutepath val imgname: string = "img/%s_%d_%d_%d.jpeg".format(splitfilename(images(i).getname), width, height, cnt) pool.execute(new imageworker(imgsrc, imgname, width, height)) } } pool.shutdown() pool.awaittermination(long.maxvalue, timeunit.nanoseconds) } // split file name def splitfilename(filename: string) = { filename.substring(0, filename.lastindexof(".")) } }
imageresizer
copy work. reads image bufferedimage
, resizes new bufferedimage
, , writes jpeg
file.
imageworker
thread work. executed worker threads in executeservive
.
imagegenerate
dispatching work. reads image files in args(0)
(first arg), generates new random width , height, , submit new job pool
.
compile , run: scalac imagegenerate.scala
scala generate.image.imagegenerate test
. sizes of images 150kb in average.
as running, program throws java.lang.outofmemoryerror
. sometimes, there exception in thread "pool-1-thread-36" java.lang.outofmemoryerror: gc overhead limit exceeded
error.
if set parameter -j-xmx2048m
, program run smoothly. however, run 400 images. there optimization code?
thanks sharing idea, best wishes.
you should calling dispose()
something (untested)
val graphics = buffimg.getgraphics() graphics.drawimage( srcimg.getscaledinstance(width, height, image.scale_smooth), 0, 0, null ) imageio.write(buffimg, "jpeg", new file(distimgpath)) graphics.dispose()
Comments
Post a Comment