halcyon / asdf-java

A Java plugin for asdf-vm.
MIT License
466 stars 85 forks source link

set-java-home.zsh is painfully slow; can we make it only run on startup and when the user changes their directory? #193

Open jjinux opened 1 year ago

jjinux commented 1 year ago

When you use, . ~/.asdf/plugins/java/set-java-home.zsh, it sets up some code to run before every command in order to set JAVA_HOME. This is painfully slow since it executes asdf which java. Even just hitting ^c causes my system to lag 0.7 seconds.

It'd be better if this code only ran on startup and when changing directories. Or, at least, it'd be nice to have a built-in option to make it work that way.

As a workaround, I'm using the following in my ~/.zshrc:

. <( sed 's/add-zsh-hook precmd asdf_update_java_home/add-zsh-hook chpwd asdf_update_java_home; asdf_update_java_home/' < ~/.asdf/plugins/java/set-java-home.zsh )

Now, it'll only work on startup and when changing directories.

Sorry, I don't know how to do the same thing for all of the other shells :-/

bklebe commented 1 year ago

Here's my hack:

java() {
  . ~/.asdf/plugins/java/set-java-home.zsh
  add-zsh-hook -d precmd asdf_update_java_home
  $(asdf which java) "$@"
}

Works for interactive mode at least. Not sure if scripts will pick it up.

AlexMackechnie commented 1 year ago

I've done something similar to @bklebe's solution above.

I have a function that runs on shell initialization to update JAVA_HOME based on the global Java version I have set, and an extra function to perform 2 actions that I run whenever I want to switch version in the current shell:

  1. Switch the shell-scoped Java version.
  2. Update the JAVA_HOME based on the new version.
asdf_update_java_home() {
  local java_path
  java_path="$(asdf which java)"
  if [[ -n "${java_path}" ]]; then
    export JAVA_HOME
    JAVA_HOME="$(dirname "$(dirname "${java_path:A}")")"
    export JDK_HOME=${JAVA_HOME}
  fi
}
asdf_update_java_home

asdf_shell_java() {
  asdf shell java $1 
  asdf_update_java_home
}

Whenever I want to switch Java version, I just run:

asdf_shell_java <new-version>

Caveat is that it doesn't work for asdf local, but I tend to only use global and shell so this works for me.

jjinux commented 1 year ago

@bklebe's approach would make Java take 3 seconds or so every time you ran the java command, right?

And @AlexMackechnie's approach requires you to remember to execute a command.

My approach runs every time you switch directories. I think it strikes a balance between being automatic and making your system slow.

bklebe commented 1 year ago

@bklebe's approach would make Java take 3 seconds or so every time you ran the java command, right?

It doesn't seem to, no.

jjinux commented 1 year ago

My bad. It's not 3 seconds. asdf which java takes about 0.5 seconds on my machine.

jdx commented 1 year ago

try rtx, it updates JAVA_HOME without any need for set-java-home.zsh and doesn't have any meaningful performance impact.