Part-2: Web Start Application: Concurrency Issue

▼魔方 西西 提交于 2019-12-02 08:53:13

问题


With your suggestions given on this thread,

I tried using FileLock, however, when I write something in the file, somehow excel file gets corrupted and there is nothing in the file (it gets empty, no contents in there)

I have the following method:

void writeIntoTheFile(XSSFWorkbook defectWorkBook, File fileToWrite) {

            FileLock lock = null;
            FileChannel channel = null;
            FileOutputStream out = null;
            try {
                //fileToWrite contains an excel .xlsx file
                channel = new RandomAccessFile(fileToWrite, "rw").getChannel();
                lock = channel.tryLock();
                if (lock != null) {
                    out = new FileOutputStream(fileToWrite.getPath());
                    defectWorkBook.write(out);

                } else {
                    JOptionPane.showMessageDialog(null, "Another instance is already writing, Try after a few seconds.", "Write Error...", JOptionPane.INFORMATION_MESSAGE);
                }
                    out.close();

            } catch (Exception e) {
                e.getMessage();
            } 


           finally{   
            if (lock != null && lock.isValid()) {
                    lock.release();
                }
            channel.close();

            } 

        }

Seems the problem is coming from below code:

channel = new RandomAccessFile(fileToWrite, "rw").getChannel();
 lock = channel.tryLock();

Can anyone please help me on this issue?

rahul


回答1:


I suspect you are getting an exception in your try{} block, but your catch clock doesn't prin it. e.getMessage() will get the message but not print it.

I suggest something along the lines of e.printStackTrace() (for a production system you would want to do something more useful with the exception).



来源:https://stackoverflow.com/questions/7736530/part-2-web-start-application-concurrency-issue

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