Air Wei
Air Wei

Reputation: 19

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");
         // ...
    }
}

Upvotes: 1

Views: 42

Answers (3)

CodeScale
CodeScale

Reputation: 3314

I Don’t get the point of what you’re trying to achieve here but as you always return a new instance of subresource class it won’t have any competing access here. Unsafe = Nope.

Upvotes: 1

Ajit Saha
Ajit Saha

Reputation: 22

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.

Upvotes: 1

Simon Kocurek
Simon Kocurek

Reputation: 2166

REST endpoints are not thread safe.

When multiple users call the endpoint at the same time, multiple threads will run the same functionality.

However, your code should be safe, as the hash map data is not shared between threads.

Upvotes: 0

Related Questions