Java Preferences not working in snap app

I have a Java app that I packaged using snapcraft. It works for most part except when my app trying to update user registry using Java Preferences I get this error:

java.lang.RuntimeException: java.lang.SecurityException: Could not lock User prefs. Lock file access denied.
	at runiter.calculator.MainApplication.lambda$windowActivated$10(MainApplication.java:250)
	at java.base/java.lang.ThreadGroup.uncaughtException(Unknown Source)
	at java.base/java.lang.ThreadGroup.uncaughtException(Unknown Source)
	at java.base/java.lang.Thread.dispatchUncaughtException(Unknown Source)
Caused by: java.lang.SecurityException: Could not lock User prefs. Lock file access denied.
	at java.prefs/java.util.prefs.FileSystemPreferences.checkLockFile0ErrorCode(Unknown Source)
	at java.prefs/java.util.prefs.FileSystemPreferences.lockFile(Unknown Source)
	at java.prefs/java.util.prefs.FileSystemPreferences.sync(Unknown Source)
	at java.prefs/java.util.prefs.FileSystemPreferences.flush(Unknown Source)
	at java.prefs/java.util.prefs.FileSystemPreferences.syncWorld(Unknown Source)
	at java.prefs/java.util.prefs.FileSystemPreferences$3.run(Unknown Source)
	at java.base/java.util.TimerThread.mainLoop(Unknown Source)
	at java.base/java.util.TimerThread.run(Unknown Source)

The file that Java is trying to lock is this: /home/saeid/.java/.userPrefs/.user.lock.saeid

I tried adding this plugs to my snapcraft.yaml but it didn’t help:

plugs:
  java-preferences:
    interface: personal-files
    write:
      - $HOME/.java/.userPrefs/.user.lock.saeid

Any help is appreciated.

Sorry for what might be a silly question, Is the interface connected?

If JAVA is using $HOME, and you have the home interface plugged, it would resolve to ~/snap/<snap-name>/current

It must be connected because I can actually read and write to that file. But I can’t lock that file.

Java doesn’t use $HOME, I think it might read /etc/passwd directly or something similar, but regardless, try adding this to your snap:

environment:
    _JAVA_OPTIONS: -Duser.home="$SNAP_USER_DATA"