English 中文(简体)
如何在贾瓦以可怕的安全方式使用 m子?
原标题:How to use mkdirs in a thread safe manner in Java?

我在经历过 m子和环网周围的 p事之后,给人留下的印象是,与 m子手存在着可怕的安全问题。

如果有可能出现多种透镜试图建立类似档案结构,那么是否可确保适当设立名录?

增 编

(在我的案件中,我将在安乐斯使用这个词)

最佳回答

奥凯,我知道,尽管如此,但我认为也许有一个简单的解决办法。 你在关于这个问题的评论中联系的这篇文章似乎表明,唯一的问题就是正在创建的名录not。 解决办法是:

if (!f.mkdirs()) {
    f.mkdirs();
}

然而,这似乎效率不高,可能仍然存在问题。 因此,为什么不简单地这样做:

while (!f.mkdirs()) {}

简单但行之有效。

EDIT:在考虑一条轨道后,这个例子可能会滞后,并可能造成lock锁。 因此,这可能是一个更好的想法:

while (!f.mkdirs()) { Thread.yield(); }

当然,只有在你能够 re夜,而且不会出现高度优先的情况时,才建议这样做。 就此说几句。

问题回答

我不敢肯定安康是否支持并行的一揽子计划,但我在此认为:

private static Lock fsLock = new ReentrantLock();

private void mkdir( File dir ) throws FileNotFoundException {

    if( dir.exists() ) {
        return;
    }

    fsLock.lock();
    try {
        if( !dir.exists() ) {
            log.info( "Creating directory {}", dir.getAbsolutePath() );
            if( !dir.mkdirs() ) {
                throw new FileNotFoundException( "Can t create directory " + dir.getAbsolutePath() );
            }
        }
    } finally {
        fsLock.unlock();
    }
}

The method returns early if the directory already exists. If it doesn t exist, only one thread will try to create it.

Do all your directory creation in a worker thread that serializes everything. You can use a Looper and a Handler to make it easy to post Runnables that call mkdirs to your worker thread. When you re done making directories, you can call Looper.quit() to end the thread after it processes the last posted Runnable. The documentation for Looper has sample code that shows how near to trivial this is to do.

One possible solution would be a MkDirService (illustrated below) that guarantees only one instance and runs in it s own thread. Making use of BlockingQueue.

第一,该处:

package mkdir;

import java.io.File;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MkDirService extends Thread {

    private static MkDirService service;
    private BlockingQueue<File> pendingDirs = new LinkedBlockingQueue<File>();
    private boolean run = true;

    private MkDirService() {
    }

    public synchronized static MkDirService getService() {
        if (service == null) {
            service = new MkDirService();
            new Thread(service).start();
        }
        return service;
    }

    public void makeDir(File dir) {
        pendingDirs.add(dir);
    }

    public void shutdown() {
        run = false;
    }

    @Override
    public void run() {
        while (run || !pendingDirs.isEmpty()) {
            File curDir = null;
            try {
                curDir = pendingDirs.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (curDir != null && !curDir.exists()) {
                curDir.mkdir();
                System.out.println("Made: " + curDir.getAbsolutePath());
            }
        }
    }
}

试验:

package mkdir;

import java.io.File;

public class MkDirServiceTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        MkDirService mdServ = MkDirService.getService();
        mdServ.makeDir(new File("test1"));
        mdServ.makeDir(new File("test1/test2"));
        mdServ.makeDir(new File("test1/test3"));
        mdServ.shutdown();

    }
}

Eaven if this thread is a bit older I wonder if there is somethink wrong with the following solution:

package service;

import java.io.File;

public class FileService {

    public static synchronized boolean mkdirs( File dir ) {
        return dir.mkdirs();
    }
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签