Search code examples
javamultithreadingresthashmapunsafe

RESTful framework class field is safe or unsafe


jdk1.8 resin application use RESTful framework is as follows, Can only be executed through http://x.x.x.x/ws/example/subpath1 There is no other way to call Subpath1Resource So will the HashMap or String in Subpath1Resource class be unsafe?

@Path("/example")
public class ExampleResource {

    @Path("subpath1")
    public Subpath1Resource getSubpath1Resource() {
        return new Subpath1Resource();
    }
}

public class Subpath1Resource {
    private HashMap<String, String> dataHead;
    private String p_no;
    private String p_name;
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public Response createOrder(String param) {
        dataHead = new HashMap<>();
        String[] aParam = param.split("/");
        p_no= aParam[0];
        p_name=aParam[1];
        dataHead.put("p_no",aParam[0]);
        dataHead.put("p_name",aParam[1]);
        processOrder(); 
        return Response.ok(currentOrder).build();
    }

    private void processOrder() {
    String _p_no = dataHead.get("p_no");
    String _p_name = dataHead.get("p_name");
         // ...
    }
}


Solution

  • when a request come to server to access RESTful resource then a thread will be created. Therefore multiple request ill create multiple threads. Now HashMap is not thread-safe. Therefore ConcurrentHashMap is right implementation for using RESTful resource.