0

我希望我的类只有一个实例 Format1 应该通过类引擎返回:

 public final class Engine {

     private static Format format;

     public Engine(final Param1 param1, final Param2 param2) {
         Engine.format = new FormatV1(param1);   // FormatV1 implements Format
     }

     static Format getFormat(int condition) {
         switch(condition) {
            case 1 : return format;
         }
     }
 }

这是否确保通过 getFormat 只返回一个正确的 Format 实例?

此外,调用 getFormat() 的客户端需要在格式对象(绝对没有状态)上执行方法,但将 ByteBuffer 传递给方法(此 ByteBuffer 可能会被修改):

 class Client 
 {
     public static void main(String[] args) {

          Format obj = Engine.getFormat(1); // some param
          ByteBuffer buffer;                // read data from disk

          synchronized (obj) {

                 long[] result = obj.method(buffer);

                 if (result == null) {
                      // do something
                 }
          }
     }
 }

这里/这样的同步构造是否确保可序列化?

PS:我对Java很陌生,据我所知,我也可以使方法同步,但我认为检查(结果== null)也应该包含在关键部分中,所以我决定使用同步(obj ) 构造。如果这是一个愚蠢的问题,请原谅我,但我想确认我的怀疑。

4

2 回答 2

0

目前,您正在 Engine 构造函数中创建 Format 实例,这很可能不是您想要的(您当前的示例将抛出 NullPointerException。

其次,您有两个同步问题。首先是格式实例的正确发布。你目前不这样做。您应该使用类初始化(在类创建时实例化格式实例)或使格式成员易失,以便正确发布格式实例。

其次,如果您的格式实例具有可变状态,那么您应该使 FormatV1 方法本身同步。在使用对象之前让调用者在对象上同步是一个非常糟糕的设计。

于 2013-09-11T18:16:32.000 回答
0

您创建了 Engine 类的构造函数来初始化静态变量,而是创建一个静态初始化器,在该方法上使用同步

public static synchronized void initFormat(....) {
   if (format == null) {
      ... create it
   } else {
   .... your chocie: throw an exception or do nothing 
   }
}
于 2013-09-11T18:16:34.513 回答