views:

75

answers:

5

I'm re-working a Java executable that may be started multiple times, and I want the process to proceed one at a time. In C# I would do this with a named/system Mutex, but this doesn't seem to be possible in Java. How can I achieve this functionality?

+2  A: 

You can use exclusive access to a File on the File System to achieve similar behavior. I don't think there is something similar to what you've mentioned.

Examples

Pablo Santa Cruz
@Pablo, how would you go about getting exclusive access to a file?
C. Ross
Chick this out: http://forums.sun.com/thread.jspa?threadID=465792
Pablo Santa Cruz
http://java.sun.com/j2se/1.5.0/docs/api/java/nio/channels/FileLock.html
Alan Krueger
A: 

Each time you start Java executable, you start a new instance of Java Virtual Machine (JVM). They are like a different workstations. That's why there is no such a thing like system mutex in Java.

Antonio
I understand that they are in different runtimes/processes, but many (most?) operating systems provide a system mutex feature. Does Java not have a way to access it?
C. Ross
The problem is that Mutex is a synchronization tool. If you write a native app, mutexes can be used to synchronize threads (or processes) in bounds of a single machine.But if you write a Java app, than your mutes is java.lang.Object. It has wait/notify methods, but they make sense only in bounds of a single machine (JVM).An example: Java cloud hosting at Google App Engine. It create new JVMs on demand. Programmer do not know if a new JVM is created at the same host or at an another node of the cluster.
Antonio
That's the same story for e.g. .NET applications - they however do have named mutexes. Short story is, Java does not.
nos
A: 

If your operating system provides these mutexes, perhaps you could do with with a native library? ( http://en.wikipedia.org/wiki/Java_Native_Interface ) Of course, you'll be accessing this resource in a OS-specific way, so you'll lose the portability that pure Java gives you.

Curtis
+1  A: 

Java is a least common denominator tool that provides functionality that is common to all platforms it runs on, that is if it has been implemented yet.
You could use JNA (A simplified way to access native functionality)

In the past I have used sockets to make sure that a program could not start if one was running.
As indicated elsewhere a File based Semaphore could work, of course a downside to this is if the program crashes then your semaphore has to be manually reset.

Romain Hippeau
A: 

Remember that Java runs under a Java Virtual Machine. Like OS-level synchronization mechanisms generally only affect the machine on which it runs, native Java synchronization mechanisms only work within that JVM.

Trying to prevent multiple JVMs from being launched to do something is analogous to trying to prevent an application from being run at the same time on multiple physical machines, and is probably not worth the effort.

Alan Krueger