When I open a Java Program, I want a method which returns true if the program is already running, and false otherwise. Is there a way to check for this?

For example, say we open our web browser, the first time we open it, i want the method to return false (there are no other instances of this program running). Now if I were to open a new copy of the program it would return true since there is already one copy of it open.

There's no generic way.

One method that's generally advocated is to open a serversocket on an obscure port on the primary network interface on the first instance that starts.
This socket does nothing, it just sits there as a marker.

New instances that want to start cannot open a serversocket on that same port because only one server can run on any port on any given network interface.

But what if a user downloads aol instant messenger, or some other internet program that uses the port the same as mine? BitTorrent (which uses serveral, yahoo messenger, there are a ton of programs which use a ton of ports). I obviously can't go and check to see which one of these all of these program use (especially since you can easily change there defaults)

Several ways:
1. JNI - Windows API functions - here are differents ways.
2. Simple - once opened program will write a file somewhere and new
instance will check first exists this file or not - there are a lot of similar examples
for C++ lessons.

lol, what if the program crahes or the operating system crashes/turns off/restarts/etc... and the file is left there for all eterninity! then the program will never be able to be opened again!

that's exactly why you should not use a lockfile UNLESS you also include a mechanism to remove the lockfile forcibly (which should then also cause any other instances of the application to terminate for example).

If another program tries to use that port it's out of luck, pure and simple.
The programs you mention are I think smart enough to hop to another port if the one they want isn't available (and in a mission commercial environment shouldn't be installed anyway).

writing to a file is a solution but in order to prevent from OS crashes you can log when do the program starts and stops, so if OS crashes when your program is running, if you rerun your program and it sees that program didn't stop properly, and starts itself...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.