本文介绍了将Terracotta用于(分布式)共享Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不同的Java进程之间共享实例/对象?

How do you share an instance / object across different Java processes?

EnvironmentConfig config = new EnvironmentConfig();
config.setLogLockTimeout(3000);
config.setManagementEnabled(false);
config.setEnvCloseForcedly(true);
Environment env = Environments.newInstance(dbPath, config);
environmentMap.put(dbPath, env);

上面的这段代码中,Environment类不是Serializable并且该对象可在整个应用程序过程中与以下对象一起使用:

It this code above, the Environment class is not Serializableand this object is used across the application process with:

Environment env = environmentMap.get(dbPath);

然后按以下方式使用:

EntityId[] id = null;
new PersistentEntityStoreBuilder(env).transact(txn -> {
    id[0] = txn.createEntity(comparableMap);
});
return id[0];

Environment是嵌入式数据库的接口,该接口在首次访问它的进程中被锁定.就是说,其他进程无法再访问数据库,因此,为了使其他进程访问数据库,它需要与第一环境完全相同的实例.那就是共享"的地方. Java对象需求根源.

This Environment is the interface to the embedded database that is locked within the process that first accessed it. Meaning to say, other processes cannot access the database anymore thus in order for the other processes to access the database it needs the very same instance of the first Environment. That is where the "shared" Java object requirements roots.

现在,我需要能够在不同的应用程序流程中使用相同的对象(环境),我知道这在标准JVM上本身不是可行的,Terracotta如何处理有用这样的要求,我一直在阅读,Terracotta实际上可以使多个JVM进程充当一个,所以我认为这可能是合适的解决方案.

Now I need to be able to use this same object (the Environment) across different application processes, I understand that this is not natively doable with the standard JVM, how would Terracotta be useful to handle such a requirement, I've been reading that Terracotta, in fact, can make multiple JVM processes act as one, so I thought that it might be the suitable solution.

文档指出:

如果兵马俑无法做到这一点,您能解释为什么吗?如果可能的话,怎么办?

If this is not possible with Terracotta, can you explain why? If this is possible, how?

推荐答案

通过阅读更多该文档(您可以自己完成),看来Terracotta是基于字节码检测的,实际上可以透明地共享整个文档.跨在不同机器上运行的JVM的对象图.

From reading a bit more of that document (which you could have done yourself), it looks like Terracotta is based on bytecode instrumentation and can in fact transparently share entire object graphs across JVMs running on separate machines.

因此,原则上它应该为您工作环境类 如果它是嵌入式数据库",它后面的内存可以完全在内存中运行,并且不会像使用本机代码那样疯狂地执行任何操作.

So in principle it should work for you Environment class if it the "embedded database" behind it runs fully in memory and doesn't do anything crazy like using native code.

它是否在实践中有效,尤其是它将对性能产生什么影响,您只需尝试一下即可.

Whether it works in practice and especially what effect it will have on performance is something you'll just have to try out.

这篇关于将Terracotta用于(分布式)共享Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 06:59