9

We have a situation where we take up a Jetty instance inside the VM that runs gradle.

However, this fails pretty badly when we are running inside a gradle daemon: We don't get rid of the Jetty instance totally, so it have to die with the gradle process itself. (However, that is not really of a big concern, since we do not want the gradle daemon in this CI integration tests case anyway).

So, we would like to know whether the current task is running inside a gradle daemon, or not - so that we can throw an exception or otherwise inform the user that this is the wrong approach, please run this un-daemonized.

Will
  • 24,082
  • 14
  • 97
  • 108
stolsvik
  • 5,253
  • 7
  • 43
  • 52
  • 1
    Maybe I don't understand what you're after, but does `Thread.currentThread().isDaemon()` not work? – superEb May 15 '14 at 15:15
  • Gradle have this "daemon configuration" whereby the first gradle-command you issue fires up the daemon process, and the subsequent commands just talks to this process. This is so that you don't incur the startup cost for the JVM and parsing files etc - you get pretty much "instant reaction" to issued commands. However, this daemon lives forever (or until you kill it), and since the JVM can become "polluted" by loaded classes etc., it should be possible to know from within the Gradle-script whether it is being run inside a deamon or not. – stolsvik Jun 25 '14 at 13:39

3 Answers3

7

Gradle names one of its thread "Daemon thread" so if you allow a hack, this could work:

def isDaemon = Thread.allStackTraces.keySet.any { it.name.contains "Daemon" };
Knut Saua Mathiesen
  • 1,020
  • 10
  • 19
2

Another solution would be to read the "sun.java.command" property.

If you are in the daemon the value for gradle 2.5 is

org.gradle.launcher.daemon.bootstrap.GradleDaemon 2.5

and if you are not the value is

org.gradle.launcher.GradleMain taskName

so a simple

if (System.properties.'sun.java.command'.contains('launcher.daemon')) {
  println 'Daemon is true'
} else {
  println 'Daemon is false'
}

would do the trick too

Hillkorn
  • 633
  • 4
  • 12
0

I wanted to know this from the context of a gradle plugin. After checking out the gradle source I eventually found the answer using:

val daemonScanInfo: DaemonScanInfo? = (project as DefaultProject).services.get(DaemonScanInfo::class.java)
val runningAsDaemon = !daemonScanInfo.isSingleUse

This had the benefit of being able to detect --no-daemon aswell as defining org.gradle.daemon=true|false. Doing project.findProperty("org.gradle.jvmargs") didn't catch --no-daemon on the command line.