java - Java中的跨进程同步

标签 java windows multithreading

如何同步在 Windows 上运行的两个 Java 进程?

我正在寻找类似于 Win32 Named Mutex 对象的东西,它允许两个进程使用相同的锁定对象。

谢谢

最佳答案

Java跨进程锁:

// Tester
try {
    if (crossProcessLockAcquire(SomeClassInYourApp.class, 3000)) {
       // Success - This process now has the lock. (Don't keep it too long.)
    }
    else {
       // Fail (Timeout) - Another process still had the lock after 3 seconds.
    }
} finally {
    crossProcessLockRelease(); // try/finally is very important.
}

// Acquire - Returns success ( true/false )
private static boolean crossProcessLockAcquire(final Class<?> c, final long waitMS) {
    if (fileLock == null && c != null && waitMS > 0) {
        try {
            long dropDeadTime = System.currentTimeMillis() + waitMS;
            File file = new File(lockTempDir, c.getName() + ".lock");
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            FileChannel fileChannel = randomAccessFile.getChannel();
            while (System.currentTimeMillis() < dropDeadTime) {
                fileLock = fileChannel.tryLock();
                if (fileLock != null) {
                    break;
                }
                Thread.sleep(250); // 4 attempts/sec
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return fileLock == null ? false : true;
}

// Release
private static void crossProcessLockRelease() {
    if (fileLock != null) {
        try {
            fileLock.release();
            fileLock = null;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// Some class vars and a failsafe lock release.
private static File lockTempDir = new File(System.getProperty("java.io.tmpdir") + File.separator + "locks");
private static FileLock fileLock = null;
static {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run(){
            crossProcessLockRelease();
        }
    });
}    

关于java - Java中的跨进程同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5297813/

相关文章:

c++ - 返回类型 Pthread 使用 C++ 创建

.net - 同步锁的种类

java - 为什么非同步对象比同步对象执行得更好?

java - 如何通过Java获取linux上电脑的ip?

java - 需要java编程方面的帮助!

java - 使用进程 ID 和线程 ID 命名目录

java - 获取所有可以处理 Intent.ACTION_MEDIA_BUTTON Android 13 API33 的 android 包

c++ - 在 Windows 7 中交叉编译 C 和 C++ 应用程序,在 linux 下使用 MinGW

c++ - 进程列表及其子进程

c - 无法在 C 中打开文件