Skip to content

Instantly share code, notes, and snippets.

@franciscoafonsoo
Last active July 13, 2022 17:06
Show Gist options
  • Save franciscoafonsoo/734cabcf3d1f9c5488eef8b252de358a to your computer and use it in GitHub Desktop.
Save franciscoafonsoo/734cabcf3d1f9c5488eef8b252de358a to your computer and use it in GitHub Desktop.

Properly manage Java versions in macOS

After spending hours reading half baked or old medium articles explaining how to setup java in macOS, I made an updated version that covers what I think are the best tricks.

1. uninstall all existing jdk releases (if any)

AdoptOpenJdk

# remove any versions. autocomplete should help

brew uninstall adoptopenjdk8
brew untap AdoptOpenJDK/openjdk

OpenJDK

# same as before: remove the respective versions
brew uninstall openjdk8

2. install eclipse temurin versions

AdoptOpenJDK is moving to Eclipse so installing the Eclipse Temurin is the way to go.

# Install Java 17.
# replace 8 with 11, 15, etc for different versions
brew tap homebrew/cask-versions
brew install --cask temurin8

3. setup jenv

A long time ago, rbenv provided a solid and easy way to manage several versions of ruby. After this, good spin offs were made like pyenv and some terrible like nvm.

In Java case, jenv seems to be the best one, mirroring rbenv commands and style.

brew install jenv

DON'T FOLLOW THE OFFICIAL INSTRUCTIONS

Doing eval "$(jenv init -)" will seriously slowdown your terminal (a common problem for this types of problems). But there is a easy way around this which is to lazy load jenv.

4. lazy load jenv

This script is available for zsh. It might be simple to replicate in bash, but since most macOS's nowadays use zsh anyway, i will focus on it.

4.1 with oh-my-zsh

Simply close and use

# Clone to custom plugins
git clone https://github.com/shihyuho/zsh-jenv-lazy .oh-my-zsh/custom/plugins/jenv-lazy

Add the plugin to your plugin list in .zshrc

# .zshrc
plugins=(... pyenv-lazy jenv-lazy)

4.2 with vanilla zsh

Clone this to any folder (I will clone it to .config/zsh/plugins)

git clone https://github.com/shihyuho/zsh-jenv-lazy ~/.config/zsh/plugins/jenv-lazy

source it in the .zshrc

#.zshrc
source ~/.config/zsh/plugins/jenv-lazy/jenv-lazy.plugin.zsh

5. Configure jenv

Like explained in the jenv website, add the java versions installed into jenv.

# depending on the version, replace the 17
jenv add /Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home/

6. Optional: set the global with a proper java version

It might be good to use one of this versions by default. So just do this:

jenv global 17.0.3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment