Singleton在Glassfish Server

时间:2017-06-04 00:55:58

标签: java java-ee intellij-idea glassfish singleton

我的单身人士称为资源。它只能通过我使用的Singleton标准实例化一次:



package site.kevindhu.models;

import site.kevindhu.entity.Player;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

public class Resources {
    public static Resources resources;
    public Map<String, Object> data;

    static {
        resources = new Resources();
    }

    private Resources() {
        data = new HashMap<>();
        data.put("players", new HashSet<Player>());
        data.put("newPlayers", new HashSet<Player>());
    }


    public static Resources getInstance() {
        return resources;
    }
}
&#13;
&#13;
&#13;

但是,它无法正常工作!

当我部署.ear来运行我的glassfish服务器时,它会进入这个块两次:

&#13;
&#13;
static {
        resources = new Resources();
    }
&#13;
&#13;
&#13;

结果,&#34;单身&#34;实际上每次运行服务器时都会创建两个不同的资源。

我知道我做了两次,因为每当我尝试调用Resources.resources时,我调试它会调用两个不同的Resources对象。

这可能是因为我正在部署.ear文件吗?这个双实例化的细节如何工作?

1 个答案:

答案 0 :(得分:0)

最好的方法是让编译器为你处理它:

/** Singleton. */
public enum Resources {
  RESOURCES;

  private final Map<String, Team> teams = new HashMap<>();

  public boolean add(Team team) {
    return team != null
        && teams.put(team.getName(), team) == null;
  }

  public Team find(String name) {
    return name == null ? null : teams.get(name);
  }

  public Team find(Team team) {
    return team == null ? null : get(team.getName());
  }

  public Map<String, Team> getTeams() {
    return Collections.unmodifiableMap(teams);
  }

  // remove, iterators, etc.
}

public class TeamImpl implements Team {
  private final String name;
  private final Map<String, Player> roster = new HashMap<>();

  public TeamImpl(String name) {
    if (name == null) {
      throw new IllegalArgumentException("name must not be null");
    }
    this.name = name;
    assert this.name != null;
  }

  @Override
  public boolean equals(Object other) {
    // base comparison on team name 
  }

  @Override
  public int hashCode() {
    assert this.name != null;
    return name.hashCode();
  }

  // methods from interface Team:

  @Override
  public String getName() {
    return name;
  }

  @Override
  public Set<Player> getRoster() {
    return Collections.unmodifiableSet(new HashSet<>(roster.values()));
  }

  @Override
  public boolean add(Player player) {
    return player != null
        && roster.put(player.getName(), player) == null;
  }

  @Override
  public Player find(String name) {
    return name == null ? null : roster.get(name);
  }

  // remove, iterators, etc.
}