synchronizedMap对于不同的类是常见的

时间:2017-12-15 13:47:03

标签: java synchronization

我有一个web servlet类,它存储了synchronizedMap中请求的所有响应。 我还有RabbitMQ消息处理程序(侦听器),它运行在单独的线程中。在消息接收时,此消息处理程序发送响应并从映射中删除请求。 我在每个请求中都将元素放在地图中:

@WebServlet({"/create_conf_link", "/invite_participant", "/get_conf_credentials", "/get_web_conf_credentials"})
public class VcmsServlet extends HttpServlet implements AutoCloseable {
    private static final long serialVersionUID = 1L;

private final VcmsWsMessageHandler mMessageHandler;

private volatile Map<String, HttpServletResponse> mResponses = Collections.synchronizedMap(new HashMap<String, HttpServletResponse>());

/**
 * @see HttpServlet#HttpServlet()
 */
public VcmsServlet() 
{    
    super();

    mMessageHandler = new VcmsWsMessageHandler(mResponses);
}


/** 
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request
 * @param response servlet response
 */
 protected void handleRequest(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
 {
     String corrID = java.util.UUID.randomUUID().toString();
     mResponses.put(corrID, response);

在MessageHandler类

中调用消息句柄handle方法
public class VcmsWsMessageHandler implements IMessageHandler 
{
    public VcmsWsMessageHandler(Map<String, HttpServletResponse> responses) 
    {
        mResponses = responses;
    }

@Override
public void handle(final String inMethod, final String inMessage, final BasicProperties inProperties)
{
    String corrID = inProperties.getCorrelationId();
    LOG.info("VCMS response for " + corrID + ": " + inMessage);
    synchronized (mResponses)
    {
        HttpServletResponse response = mResponses.get(corrID);

        if(response == null)
            LOG.error("Failed to find response object for corrilcation ID " + corrID);
        try
        {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(inMessage);
            mResponses.remove(corrID);
        }
        catch(IOException ex)
        {
            LOG.error("Error sending response");
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        }
    }
}

private volatile Map<String, HttpServletResponse> mResponses;
}

问题在于MessageHandler类中对应的corrID没有响应,尽管在servlet的handleRequest方法中添加了map元素。 HttpServletResponse response = mResponses.get(corrID);返回null。但在极少数情况下,mResponses.get(corrID);会返回有效响应,一切正常。 我应该如何使用map在类之间进行同步? 感谢。

0 个答案:

没有答案