Skip to content

Caching

Caching

Java supports jcache layer for MT connectors and/or other drivers. OmegaT uses Caffeine cache library for the purpose.

How to create cache object

Here is complete example how cache is used.

public class Exmaple {
    private final Cache<String, String> cache;

    public Example() {
        cache = getCaffeineCache("ExampleCache");
        CoreEvents.registerProjectChangeListener(eventType -> cache.clear());
    }

    protected Cache<String, String> getCafeineCache(String name) {
        CachingProvider provider = Caching.getCachingProvider();
        CacheManager manager = provider.getCacheManager();
        Cache<String, String> cache1 = manager.getCache(name);
        if (cache1 != null) {
            return cache1;
        }
        CaffeineConfiguration<String,String> config = new CaffeineConfiguration<>();
        config.setExpiryPolicyFactory(() -> new CreatedExpiryPolicy(Duration.ONE_DAY));
        config.setMaximumSize(OptionalLong.of(1000));
        return manager.createCache(name, config);
    }

    public String translate(String text) {
        String result;
        result = cache.get(text);
        if (result == null) {  // when there is no cache hit.
            result = query(text);
            if (result != null) {
                cache.put(text, result);  // remember for future
            }
        }
        return result;
    }

    private String query(String text) {
        // actual qeury for web service.
    }
}

You will want to clear when project change event fired.