tags:

views:

130

answers:

4

Hi all,

I have been using Stackoverflow for a while to find solutions to my programming questions, but for the current question I haven't found a useful solution. So I joined up.

What would be a good solution to limit a Java applet to only one instance. I'm using php to serve the applet to the end user, so that would be an option.

But I'm much more interested if I can limit the execution of an Java Applet through the Applet itself. I'm pretty new to Java so I don't really know where to start looking for a construction like that.

Any suggestions would be appreciated.

As a side note, " javascript to launch only ONE window for a Java applet with a given URL" would be a solution. Although I'm embedding the applet into the application I'm building and I'm not really keen on a popup serving the applet.

Sincerely, AltWouss

Edit:
To clarify the instance limit. I would like to have only one applet loaded per machine.

+2  A: 

Why don't you start a SocketServer on a well known port for your applet ?

If opening that SocketServer, it may be due to the fact that another one is already running. Then, you can display a message telling so.

Riduidel
Would this throw a "java.security.AccessControlException"?
AltWouss
It depends upon your applet's permission.
Riduidel
For some time now applets have been allowed to listen on ports (greater than 1024, subject to OS restrictions, availability, etc). What they can't do is accept a connection from anywhere but the "same-origin" server.
Tom Hawtin - tackline
A: 

i am not really sure of this will help or not.. but the first thing that comes my mind is.. Is it possible to make the applet a singleton? sorry this is more as a follow up question then an answer...

No. that wouldn't help, as multiple applets run in different VMs
seanizer
A: 

If you use Java WebStart, then there is the JNLP SingleInstanceService.

Tom Hawtin - tackline
A: 

Unfortunately, Java does not support named mutexs for locking across processes. However, you could implement a primitive lock by simply creating a File at a know location with a known name when your applet starts. If the file cannot be created, then you know that one already exists because the application has already started once before. To ensure the file is deleted when the application closes, simple call File.deleteOnExit() method.

Something like:

if(file.createNewFile()) {
    file.deleteOnExit();
} else {
    throw new Exception("Instance already running!");
}

Not a perfect solution and certainly has some issues... But it's probably enough for what you are trying to do. Also could look at that FileLock class which could offer a more robust and appropriate solution.

S73417H