ghost4j icon indicating copy to clipboard operation
ghost4j copied to clipboard

Invalid memory access with multithreading

Open omasseau opened this issue 7 years ago • 1 comments

I'm using the high level API with the latest version of ghost4j (built from Latest commit 52cd8f2 on 5 May 2016) to convert pdfs to postscript The documentation says the high level API is thread safe.

But this does not seems the case. Here is my code:

	/**
	 * Convert a pdf file to postscript. 
	 * Note: Ghostscript must be installed on the system.
	 * @param pdfInputStream The pdf input stream.
	 * @param psOutputStream The postcript output stream.
	 * @throws Exception
	 */
	public static void convertPdfToPostscript(InputStream pdfInputStream, OutputStream psOutputStream) throws Exception {
		
		try {

			PDFDocument document = new PDFDocument();
			document.load(pdfInputStream); 
			
			PSConverter converter = new PSConverter();
			converter.setMaxProcessCount(0);
			converter.setDevice(PSConverter.OPTION_DEVICE_PS2WRITE);
			converter.convert(document, psOutputStream); 

		} catch (Exception e) {
			throw new Exception("Could not convert pdf to postscript", e);
		}
	}

But I still get an 'Invalid memory access' error when calling it from 2 threads at the same time:

java.lang.Error: Invalid memory access at com.sun.jna.Native.invokeInt(Native Method) at com.sun.jna.Function.invoke(Function.java:383) at com.sun.jna.Function.invoke(Function.java:315) at com.sun.jna.Library$Handler.invoke(Library.java:212) at com.sun.proxy.$Proxy202.gsapi_init_with_args(Unknown Source) at org.ghost4j.Ghostscript.initialize(Ghostscript.java:350) at org.ghost4j.converter.PSConverter.run(PSConverter.java:142) at org.ghost4j.converter.AbstractRemoteConverter.convert(AbstractRemoteConverter.java:85) at com.real.aof.helper.PdfHelper.convertPdfToPostscript(PdfHelper.java:2573)

omasseau avatar Aug 30 '17 15:08 omasseau

Test code to reproduce the problem:

public static void main(String[] args) throws Exception {
		
		String input = "C:/Users/maol/Developments/AOF/Tests/pdf/pdf-images/16-pages-of-text-image.pdf";
		
		final ByteArrayInputStream bais1 = new ByteArrayInputStream(Files.readAllBytes(Paths.get(input)));
		final ByteArrayInputStream bais2 = new ByteArrayInputStream(Files.readAllBytes(Paths.get(input)));
		
		final ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
		
		final ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
		
		Thread t1 = new Thread() {
			public void run() {
				try {
					convertPdfToPostscript(bais1, baos1);
				} catch (Exception e) {
					e.printStackTrace();
				}	
			}
		};
		
		Thread t2 = new Thread() {
			public void run() {
				try {
					convertPdfToPostscript(bais2, baos2);
				} catch (Exception e) {
					e.printStackTrace();
				}	
			}
		};
		
		t1.start();
		t2.start();	
	}

Tested with both Java7 and Java8

omasseau avatar Aug 30 '17 15:08 omasseau