Running Java in a Container
mesosphere.com
mesosphere.com
Setting up each one becomes a lot of work fast, so we wrote a LD_PRELOAD[1] hook that overrides sysconf[1] _NC_PROCESSORS* call to get number of processors availabale/online to a certain specified value and is baked in the docker image by default during builds.
In the .Net world there's the ThreadPool class to manage the single process-wide thread-pool, and the Task class to enqueue and orchestrate concurrent jobs (it uses ThreadPool and almost completely abstracts away the thread management).
(You could write your own thread-pool, of course, but for most code that wouldn't make sense.)
As I understand it, the JVM is rather behind in this department. (Not to mention async/await.)
Linux containers leak information about the "true" environment in a way that upset JVM assumptions before 9 and 10.
Java had thread pools and tasks since 2004 (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/conc...). For typical Java programs, no one is writing their own thread pool functionality as far as I know.
Java just lacks async/await primitives.
Java possibly makes it a bit easier to work around, really, in that Java forces you to initialize your thread pool, so it wouldn't feel quite so weird to add a "# of threads in thread pool" setting to an app config file for something. I'm guessing that's not the Docker way of doing it, though.
edit: at the end of the article, it is acknowledged that there are improvements in Java 10 and the following link is provided: https://bugs.openjdk.java.net/browse/JDK-8146115
https://reddit.com/r/java/comments/85t7dt/java_on_docker_wil...
That's why I feel platforms like Cloud Foundry are a much better fit for teams that don't have tons of container experience but want to get the benefits of a containerized runtime. The CF java buildpack[1] for example automatically handles OOM and heap settings calculation while building your application container.
disclaimer: co-founder at meshcloud, we offer a public cloud service for Cloud Foundry and K8s hosted in german datacenters.
[1] https://github.com/cloudfoundry/java-buildpackI am not sure what the plans are for Java 9 and 10 yet. Ben Hale works on JBP pretty much fulltime and the Spring team tend to experiment pretty early on JDKs. So I can't see it falling far behind.
[0] https://github.com/cloudfoundry/java-buildpack-memory-calcul...
[0]: https://medium.com/@matt_rasband/dockerizing-a-spring-boot-a... [1]: https://twitter.com/codepitbull/status/934384652806221825?s=...
Heavily encourage anyone running Java in containers to use their base image, or for larger organizations to create standard base image dockerfiles that set these JVM envvar parameters. A simple contract is: ENTRYPOINT belongs to the base image, CMD belongs to downstream application images (unless something else essential).
Just don't use vanilla "FROM openjdk:8-jre" and expect it to work. That's the worst way to kill application performance and reliability in a container.
1: https://github.com/fabric8io-images/java/blob/master/images/...
https://blogs.oracle.com/java-platform-group/java-se-support...
When we dug in further, we find its just not trouble free (i.e. experimental). The default is to use 1/4th of RAM which is entirely inefficient [2]. The "MaxRAMFraction" parameter allows to specify 1/n fraction and not possible to efficiently use 65% or 75% of memory. The only place to start is to set MaxRAMFraction=2 and that already means only 50% of memory is used for heap. That produces a lot of wastage. A lot of resource efficiency is gained by starting with 65% or 80%.
OpenJDK 10 is introducing a new option "MaxRAMPercentage" [3] and that goes closer to making a script unnecessary.
TL;DR - The default flags are still experimental in JDK 8/9, and deemed to be better on Java 10. A script is just better for consistency.
1: https://github.com/docker-library/docs/pull/900
I disagree. They seem mostly targeted at low-end cloud providers who overcommit on memory and ignore application response time (gc latency). And they don't even do a good job at this.
Their configuration uses the ParallelOld gc and tunes it to aggressively shrink the heap. What that means they don't care about frequent and long gc pauses (unless you're running small heaps below 1 GB). They just care about reducing the memory footprint of the application. On multi gigabyte heaps you accept full GCs that take several seconds. They increase the number of concurrent GC threads to the number of cores. This defeats the whole purpose of the concurrent GC threads which are supposed to run concurrently with your application without stopping it. That value should be below the number of cores.
gc logging does not work on Java 9 or Java 10
If you really care about reducing memory usage you probably should do this in addition:
-XX:-TieredCompilation hurts startup perfromance, but we just established that we don't care about performance so that's fine, but easily takes 35% out of code cache
-Xss512k cuts the thread memory usage by half, this can usually be done without any issues, often -Xss256k works as well. We run Spring inside a full profile Java EE application server with -Xss256k.
And finally the most important option of them all -XX:HeapDumpOnOutOfMemoryError is missing. You absolutely, positively need this, always. It's the only way to debug OutOfMemoryErrors.
Sadly the article mentions very little in terms of practical advice. We've tried running some small Java 8 Spring Boot containers in Kubernetes which are configured to use max ~50M heap and ~150M total off-heap yet decide to use in excess of double that memory so we end up with either a lot of OOMKills or overly large memory limits.
You can also use smaller frameworks (Vertx? Javalin? possibly Spring Boot 2). I hope that with Java 9 we won't see this amount of memory usage anymore, however our organisation isn't there yet though.
(Electron i guess being the obvious JS-to-native example)
(And isn't Sprint Boot the light-weight solution to the Sprint memory problem? /s)
In Spring Boot 2 I'm told you can can use functional beans to cut down on RAM usage. Not sure how it works.
But really, it comes down to deciding if you need a dependency or not.
As is normal for questions about Spring Boot performance, Dave Syer has done a lot of investigating: https://github.com/dsyer/spring-boot-memory-blog
If you want to be more clever, you could try this: https://github.com/cloudfoundry/java-buildpack-memory-calcul...
The absolutely most basic advice is probably: "-Xmx" does not represent the actual upper limit for memory usage. We actually most often only set 50% of the assigend memory for the jvm.
Somebody mentioned https://github.com/cloudfoundry/java-buildpack-memory-calcul... which seems pretty interesting.
IIRC it was due to a bug in glibc >= 2.1. Something about how mallocs are pooled. IIRC you need to tune it to be <= num of physical threads. Usually people advise 4 or 2.
# openjdk 8 bug: HotSpot leaking memory in long-running requests
# workaround:
# - Disable HotSpot completely with -Xint
# - slows the memory growth, but does not halt it:
MALLOC_ARENA_MAX=4
So, ensure that your java process is launched with that environment var (so, export it in the same shell, or precede your java command with it).If you happen to be using Tomcat, I recommend putting:
export MALLOC_ARENA_MAX=4
into: /usr/local/tomcat/bin/setenv.sh
As for how much memory you allocate to your containers: as of JRE 8u131 you can make this far more container-friendly: -XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap
This is equivalent to saying: -XX:MaxRAM=$(cat /sys/fs/cgroup/memory/memory.limit_in_bytes)
https://github.com/moby/moby/issues/15020
https://github.com/docker-library/openjdk/issues/57
https://bugs.openjdk.java.net/browse/JDK-8170888In fact I would rather look at serverless architecture before considering docker/Kubernetes.
or, when you have a legacy app that relies on java 6, but you want everything else to run on java 8, the ability to drop everything into a container with its runtime is a life saver.
source: I'm the devops person that's responsible for making this work
https://github.com/sladeware/groningen
Unfortunately the experiment state persistence management capability is broken.
It will be a setup where one jvm instance on the host basically serves the role of "master" in terms of class data and shared object loading while each container instance uses its memory allotment only for running computations specific to the application in that container while sharing memory objects with other containers as much as possible.
It is possible to do something similar at the moment but it requires going through a hodge-podge of painful hacks. A seamless solution to this would basically make the jvm an out of the box poor man's polyglot PaaS platform.
If you think of a typical jvm application (true for non-jvm apps as well), a significant chunk of class data will be shared since apps are typically using the same libraries (with deltas in versions), allowing easy reuse of class data across all container instances on a host would be a major scalability advance.
Java 10 will bring AppCDS via JEP 310[1]
[0]https://fosdem.org/2018/schedule/event/class_data_sharing
http://www.oracle.com/technetwork/articles/javase/mvm-141094... https://www.jcp.org/en/jsr/detail?id=121
Eclipse OpenJ9 does something like this.
> A seamless solution to this would basically make the jvm an out of the box poor man's polyglot PaaS platform.
Trying to recreate OS resource-allocation guarantees without the the OS has been a bit of a fool's errand, historically. The OS has privileged access to hardware -- it has a view of activity and an ability to enforce guarantees that processes lack.
Add to that the amount of time and effort that has gone into operating systems to cover allocation of so many different kinds of resource under so many different conditions. It is really expensive to re-engineer that capability.
I've seen a lot of attempts at trying to share ostensibly multiuser systems above the OS level and they have mostly been unhappy once there is heavy usage. Databases, queues, the JVM, everything eventually needs to be isolated from unrelated workloads at some point. Containers and VMs are much better at providing that capability.
I feel like all this cloud, container stuff is incrementally, painfully evolving towards grid computing and agents. Kinda like reinventing LISP or Prolog like features with your own 'C' runtime, instead of just using LISP or Prolog.
That said, there are practical examples to be found in common servlet containers, with some shared libraries, but individual servlets mostly firewalled from each other.
e.g. https://www.ibm.com/developerworks/library/j-multitenant-jav...
The issue is both that the security concerns were way softer than they are today, and that all your dependencies better be deplorable in a JVM too. Modern ideas of having databases deployed along with the services that need them don't work quite as well as just using OS level virtualization. That said many a crufry old company still deploys hundreds of services to production by loading .war files into a cluster of servers running JBoss or WebLogic.
Remember: Never use the standard library when a forgotten, half-assed CPAN module you can run via Perlito will kind of do.
Sadly, many Java dependencies are quite deplorable.
I wonder what we’ll be championing in another 10 years.
Edit: If the point is to encapsulate and isolate a Java application as much as possible, I would consider using a unikernel like OSv before considering Docker. This would be more efficient and also more secure.
Often, there's a mix of threads, some of which are doing CPU-intensive stuff and some which just need to do some quick thing to unblock something else, like start some new IO when some IO completes. With 1 CPU, any time any CPU-intensive stuff is happening, these quick things have to wait their turn until the next time slice. With 2 CPUs, you have twice the work and twice the likelihood of having to deal with CPU-intensive stuff, but CPU-intensive moments don't necessarily happen at the same time, so you have better odds of having one of those CPUs immediately available to do the small, quick stuff.
At least in my experience that is not true. I quite often run into this issue and the OOM-killer will only kill one of the processes inside the container, not the entire container.
>> The same is true for default memory limits. The JVM looks at the host overall memory and uses that to set its defaults.
Well, I guess if you launch a JVM anywhere without setting appropriate memory settings, you are doing something fundamentally wrong.
Hence one does not run multiple processes in the container or / and handle crashes of potential child processes correctly.
https://blog.acolyer.org/2015/05/06/blade-a-data-center-garb...