gpt4 book ai didi

java - 强制服务器等待,因为图像尚未完成写入磁盘

转载 作者:行者123 更新时间:2023-11-30 04:17:30 25 4
gpt4 key购买 nike

我有一个网站,当用户上传 PDF 文件时,它会发送到服务器,进行一些 PDF 渲染,并创建一个 .png 文件以显示为 PDF 预览缩略图。

问题是,当创建 .png 时,写入磁盘的速度比整个执行速度慢,这会导致图像在网站上显示为错误,因为它尝试访问不存在的图像(因为代码在写入磁盘完成之前完成)。

我在 .png 创建后添加了一个 Thread.sleep(2000) ,它似乎解决了问题。现在我的问题是,对于我的情况,Thread.sleep(2000) 是最好使用的代码吗?我不知道该代码是否会影响多个用户访问我的网站并上传文件。

假设用户 A 上传文件,而用户 B 正常浏览。 UserA上传文件后,UserB是否出现2秒延迟?

在这种情况下有更好的方法来暂停代码执行吗?

编辑:添加代码。我使用 PDF-Renderer 作为我的库:https://java.net/projects/pdf-renderer

public static void convertPDFtoImage () throws IOException {
RandomAccessFile raf = new RandomAccessFile (new File (rep.pathSamplePDF), "r");
FileChannel fc = raf.getChannel ();
ByteBuffer buf = fc.map (FileChannel.MapMode.READ_ONLY, 0, fc.size ());
PDFFile pdfFile = new PDFFile (buf);

PDFPage firstPage = pdfFile.getPage(1);
Rectangle2D r2d = firstPage.getBBox ();
int width = (int) r2d.getWidth ();
int height = (int) r2d.getHeight ();

Image pdfImage = firstPage.getImage(width, height, r2d, null, true, true);

BufferedImage imageToSave = (BufferedImage) pdfImage;

File outputFile = new File("public/pdfpreview/" + someName + ".png");
ImageIO.write(imageToSave, "png", outputFile); //Trying to delay this part so that it can finish writing to disk
Thread.sleep(2000) //If I put this code here, it fixes my problem.
}

最佳答案

Let's say UserA uploads a file while UserB browses normally. After UserA uploads a file, does UserB experience the 2 second delay?

只有当 UserB 和 UserA 的请求由同一线程处理时,UserB 才会遇到延迟,但事实并非如此,因为大多数 Web 服务器使用单独的线程来处理每个连接。

Thread.sleep(2000) be the best code to use?

不,这可能不是一个好方法。除了占用 cpu 之外,当您无法保证文件此时已准备好时,您还明确让线程在尝试访问文件之前等待 2 秒。最好尝试利用Java的wait()和notify()Object methods为了并发。但是,我不知道这是否有必要,因为您应该知道写入磁盘何时完成(将返回一个 java 方法)。

关于java - 强制服务器等待,因为图像尚未完成写入磁盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17974477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com