Java equivalent of fork in Java task of Ant?

2019-05-16 23:12发布

Ant Java task provides fork parameter, which, by definition "if enabled triggers the class execution in another VM". As we are dealing with a large amount of data, setting this parameter saved us from running out of Java heap space.
We want to be able to do the same through a Java class. What would be the best way to achieve the functionality as provided by fork?

标签: java ant fork
3条回答
男人必须洒脱
2楼-- · 2019-05-16 23:57

Execute another java process. By using ProcessBuilder class, for example.

http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html

You can run as many worker processes as you wish. Make them having a separate main class, doing their tasks from that main class, and quiting when their task is completed.

You'll have to figure out their classpath, and the location of java binary on the system, but that's doable.

I think you can even be notified when they complete via Process.waitFor().

查看更多
Deceive 欺骗
3楼-- · 2019-05-17 00:02

If you look at the ant source code, when fork is true, then it just wraps an Execute task and eventually, the code that gets called is

Runtime.getRuntime().exec(cmd, env);

Downloading and having a look at the source code for org.apache.tools.ant.taskdefs.Java and org.apache.tools.ant.taskdefs.Execute will give you some great pointers in finding the location of the executable to run in a platform independent way, etc.

查看更多
地球回转人心会变
4楼-- · 2019-05-17 00:05

I think you can directly use the Ant API...Ant can be directly used in a Java class. The Javadoc is available in their binary distribution.

查看更多
登录 后发表回答