Fix the following issues:

1. HashMap non-thread-safe issus
2. Fix the same problem in pr621, but use a better implementation

Add the following functions:
1. There is now a language cache inside getLanguage to prepare for different languages corresponding to different time zones where the accounts in the server are located
This commit is contained in:
Secretboy-SMR
2022-05-09 17:30:51 +08:00
committed by Melledy
parent d179b5c7dc
commit 5a37acde2b
4 changed files with 22 additions and 12 deletions

View File

@@ -6,12 +6,13 @@ import emu.grasscutter.Grasscutter;
import javax.annotation.Nullable;
import java.io.InputStream;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
public final class Language {
private final JsonObject languageData;
private final Map<String, String> cachedTranslations = new HashMap<>();
private final Map<String, String> cachedTranslations = new ConcurrentHashMap<>();
private static final Map<String, Language> cachedLanguages = new ConcurrentHashMap<>();
/**
* Creates a language instance from a code.
@@ -19,7 +20,13 @@ public final class Language {
* @return A language instance.
*/
public static Language getLanguage(String langCode) {
return new Language(langCode + ".json", Grasscutter.getConfig().DefaultLanguage.toLanguageTag() + ".json");
if (cachedLanguages.containsKey(langCode)) {
return cachedLanguages.get(langCode);
}
var languageInst = new Language(langCode + ".json", Utils.getLanguageCode(Grasscutter.getConfig().DefaultLanguage) + ".json");
cachedLanguages.put(langCode, languageInst);
return languageInst;
}
/**
@@ -42,6 +49,7 @@ public final class Language {
/**
* Reads a file and creates a language instance.
* @param fileName The name of the language file.
* @param fallback The name of the fallback language file.
*/
private Language(String fileName, String fallback) {
@Nullable JsonObject languageData = null;

View File

@@ -9,6 +9,7 @@ import java.time.temporal.TemporalAdjusters;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Locale;
import emu.grasscutter.Config;
import emu.grasscutter.Grasscutter;
@@ -306,4 +307,12 @@ public final class Utils {
return map;
}
/**
* get language code from Locale
*/
public static String getLanguageCode(Locale locale) {
return String.format("%s-%s", locale.getLanguage(), locale.getCountry());
}
}