AltWouss
AltWouss

Reputation: 135

Limit Java Applet to only one instance

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.

Upvotes: 2

Views: 1048

Answers (4)

S73417H
S73417H

Reputation: 2671

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.

Upvotes: 1

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

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

Upvotes: 1

Crazyshezy
Crazyshezy

Reputation: 1620

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...

Upvotes: 0

Riduidel
Riduidel

Reputation: 22292

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.

Upvotes: 2

Related Questions