A quick Google search give plenty answers using a simple :
Runtime.getRuntime().exec("java -jar myApp.jar"); System.exit(0);
This indeed basically works, but this answer that does not convince me for several reasons :
1) What about VM and program arguments ? (this one is secondary in fact, because can be solve it quite easily).
2) What if the main is not a jar (which is usually the case when launching from an IDE) ?
3) Most of all, what about the cleaning of the closing application ? For example if the application save some properties when closing, commit some stuffs etc.
4) We need to change the command line in the code source every time we change a parameter, the name of the jar, etc.
Overall, something that works fine for some test, sandbox use, but not a generic and elegant way in my humble opinion.
Ok, so my purpose here is to implement a method :
public static void restartApplication(Runnable runBeforeRestart) throws IOException { ... }
that could be wrapped in some jar library, and could be called, without any code modification, by any Java program, and by solving the 4 points raised previously.
Let's start by looking at each point and find a way to answer them in an elegant way (let's say the most elegant way that I found).
1) How to get the program and VM arguments ? Pretty simple, by calling a :
ManagementFactory.getRuntimeMXBean().getInputArguments();
Concerning the program arguments, the Java property sun.java.command we'll give us both the main class (or jar) and the program arguments, and both will be useful.
String[] mainCommand = System.getProperty("sun.java.command").split(" ");
2) First retrieve the java bin executable given by the java.home property :
String java = System.getProperty("java.home") + "/bin/java";
The simple case is when the application is launched from a jar. The jar name is given by a mainCommand[0], and it is in the current path, so we just have to append the application parameters mainCommand[1..n] with a -jar to get the command to execute :
String cmd = java + vmArgsOneLine + "-jar " + new File(mainCommand[0]).getPath() + mainCommand[1..n];
We'll suppose here that the Manifest of the jar is well done, and we don't need to specify either the main nor the classpath.
Second case : when the application is launched from a class. In this case, we'll specify the class path and the main class :
String cmd = java + vmArgsOneLine + "-cp \"" + System.getProperty("java.class.path") + "\" " + mainCommand[0] + mainCommand[1..n];
3) Third point, cleaning the old application before launching the new one.
To do such a trick, we'll just execute the Runtime.getRuntime().exec(cmd) in a shutdown hook.
This way, we'll be sure that everything will be properly clean up before creating the new application instance.
Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { ... } });
Run the runBeforeRestart that contains some custom code that we want to be executed before restarting the application :
if(beforeRestart != null) { beforeRestart.run(); }
And finally, call the
System.exit(0);
And we're done. Here is our generic method :
/** * Restart the current Java application * @param runBeforeRestart some custom code to be run before restarting * @throws IOException */ public static void restartApplication(Runnable runBeforeRestart) throws IOException { try { // java binary String java = System.getProperty("java.home") + "/bin/java"; // vm arguments List<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments(); StringBuffer vmArgsOneLine = new StringBuffer(); for (String arg : vmArguments) { // if it's the agent argument : we ignore it otherwise the // address of the old application and the new one will be in conflict if (!arg.contains("-agentlib")) { vmArgsOneLine.append(arg); vmArgsOneLine.append(" "); } } // init the command to execute, add the vm args final StringBuffer cmd = new StringBuffer("\"" + java + "\" " + vmArgsOneLine); // program main and program arguments (be careful a sun property. might not be supported by all JVM) String[] mainCommand = System.getProperty("sun.java.command").split(" "); // program main is a jar if (mainCommand[0].endsWith(".jar")) { // if it's a jar, add -jar mainJar cmd.append("-jar " + new File(mainCommand[0]).getPath()); } else { // else it's a .class, add the classpath and mainClass cmd.append("-cp \"" + System.getProperty("java.class.path") + "\" " + mainCommand[0]); } // finally add program arguments for (int i = 1; i < mainCommand.length; i++) { cmd.append(" "); cmd.append(mainCommand[i]); } // execute the command in a shutdown hook, to be sure that all the // resources have been disposed before restarting the application Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { Runtime.getRuntime().exec(cmd.toString()); } catch (IOException e) { e.printStackTrace(); } } }); // execute some custom code before restarting if (beforeRestart != null) { beforeRestart.run(); } // exit System.exit(0); } catch (Exception e) { // something went wrong throw new IOException("Error while trying to restart the application", e); } }
Thanks a lot! Just came across this, works like charm!
ReplyDeleteThanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained. Your article adds best knowledge to our Java Online Training from India. or learn thru Java EE Online Training Students.
DeleteI am glad that I saw this post. It is informative blog for us and we need this type of blog thanks for share this blog, Keep posting such instructional blogs and I am looking forward for your future posts. Python Projects for Students Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account. Project Center in Chennai
Deletenice tutorial... how do I call this application from a class please.
ReplyDeletevery nicely explained tutorial. But how to invoke this application from my class?
ReplyDeleteCan anybody please reply to above request??
ReplyDeleteWow, I guess I came in the perfect moment haha, JK.
ReplyDeleteJust you have to treat like a simple java method, I mean, just put it into a java class and wherever you are just make a instance of that class and call the method (restartApplication()). In the parameter you can write null if you don't have any code that you want to execute before the restarting of the application.
It works for me perfectly.
Regards :D
Thanks!! it worked i just passed null in the parameters after creating an instance and surrounding with try catch and it ran.
DeleteVery nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
ReplyDeleterpa training in bangalore
best rpa training in bangalore
RPA training in bangalore
rpa course in bangalore
rpa training in chennai
rpa online training
Thanks Admin for sharing such a useful post, I hope it’s useful to many individuals for developing their skill to get good career.
ReplyDeletepython Course in Pune
python Course institute in Chennai
python Training institute in Bangalore
Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.
ReplyDeleteAWS Course Interview Questions and Answers 2019 | AWS Interviews Questions and Answers for Devops
AWS Tutorial 2019
AWS Interview questions and answers |AWS Interview Question and Answers 2019
AWS Tutorial for Beginners 2019 | AWS Tutorial with AWS Training Videos
A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.
ReplyDeleteAWS Training in Bangalore
AWS training in sholinganallur
AWS training in Tambaram
AWS training in Velachery
Attend The Python Training in Bangalore From ExcelR. Practical Python Training in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python Training in Bangalore.
ReplyDeleteI like viewing web sites which comprehend the price of delivering the excellent useful resource Python classes in pune free of charge. I truly adored reading your posting. Thank you!
ReplyDeletewow, It is really helpful to me.I am really impressed with the way of writing of this blog. Thanks for sharing this good blog with good updates!!
ReplyDeleteMachine Learning Training in Bangalore
Attend The Data Analytics Courses in Bangalore From ExcelR. Practical Data Analytics Courses in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analytics Courses in Bangalore.
ReplyDeleteExcelR Data Analytics Courses in Bangalore
Not working when we are usung web start jnlp file.
ReplyDeletePlease suggest if have any idea .
Thanks
You can tak a look how we restart JOSM, it's working with WebStart too: https://josm.openstreetmap.de/browser/trunk/src/org/openstreetmap/josm/actions/RestartAction.java
DeleteHey, thanks for this great article I really like this post and I love your blog and also Check Python course Training in 360DIGITMG. Python Training certification program provides an overview of how Python and R programming can be employed in Data Mining of structured (RDBMS) and unstructured (Big Data) data. Comprehend the concepts of Data Preparation, Data Cleansing and Exploratory Data Analysis. Perform Text Mining to enable Customer Sentiment Analysis. Learn Machine learning and developing Machine Learning Algorithms for predictive modeling using Regression Analysis. Assimilate various black-box techniques like Neural Networks, SVM and present your findings with attractive Data Visualization techniques.
ReplyDelete360Digitmg Python Training institute
Really wonderful blog completely enjoyed reading and learning to gain the vast knowledge. Eventually, this blog helps in developing certain skills which in turn helpful in implementing those skills. Thanking the blogger for delivering such a beautiful content and keep posting the contents in upcoming days.
ReplyDeletedata science certification in bangalore
cami avizesi - cami avizeleri - avize cami - no deposit bonus forex 2021 - takipçi satın al - takipçi satın al - takipçi satın al - takipcialdim.com/tiktok-takipci-satin-al/ - instagram beğeni satın al - instagram beğeni satın al - btcturk - tiktok izlenme satın al - sms onay - youtube izlenme satın al - no deposit bonus forex 2021 - tiktok jeton hilesi - tiktok beğeni satın al - binance - takipçi satın al - uc satın al - sms onay - sms onay - tiktok takipçi satın al - tiktok beğeni satın al - twitter takipçi satın al - trend topic satın al - youtube abone satın al - instagram beğeni satın al - tiktok beğeni satın al - twitter takipçi satın al - trend topic satın al - youtube abone satın al - takipcialdim.com/instagram-begeni-satin-al/ - tiktok takipçi satın al - tiktok beğeni satın al - twitter takipçi satın al - trend topic satın al - youtube abone satın al - instagram beğeni satın al - perde modelleri - instagram takipçi satın al - takipçi satın al - instagram takipçi satın al - betboo
ReplyDeletetakipçi satın al
ReplyDeletetakipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
takipçi satın al
takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
ReplyDeleteucuz takipçi
takipçi satın al
https://takipcikenti.com
https://ucsatinal.org
instagram takipçi satın al
https://perdemodelleri.org
https://yazanadam.com
instagram takipçi satın al
balon perdeler
petek üstü perde
mutfak tül modelleri
kısa perde modelleri
fon perde modelleri
tül perde modelleri
https://atakanmedya.com
https://fatihmedya.com
https://smmpaketleri.com
https://takipcialdim.com
https://yazanadam.com
yasaklı sitelere giriş
aşk kitapları
yabancı şarkılar
sigorta sorgula
https://cozumlec.com
word indir ücretsiz
tiktok jeton hilesi
rastgele görüntülü sohbet
erkek spor ayakkabı
fitness moves
gym workouts
https://marsbahiscasino.org
http://4mcafee.com
http://paydayloansonlineare.com
ucuz takipçi
ReplyDeleteucuz takipçi
tiktok izlenme satın al
binance güvenilir mi
okex güvenilir mi
paribu güvenilir mi
bitexen güvenilir mi
coinbase güvenilir mi
instagram takipçi satın al
Informative blog
ReplyDeletebusiness analytics course in agra
seo fiyatları
ReplyDeletesaç ekimi
dedektör
instagram takipçi satın al
ankara evden eve nakliyat
fantezi iç giyim
sosyal medya yönetimi
mobil ödeme bozdurma
kripto para nasıl alınır
bitcoin nasıl alınır
ReplyDeletetiktok jeton hilesi
youtube abone satın al
gate io güvenilir mi
binance referans kimliği nedir
tiktok takipçi satın al
bitcoin nasıl alınır
mobil ödeme bozdurma
mobil ödeme bozdurma
perde modelleri
ReplyDeletesms onay
turkcell mobil ödeme bozdurma
nft nasıl alınır
Ankara evden eve nakliyat
Trafik Sigortası
DEDEKTOR
web sitesi kurma
aşk kitapları