Reputation: 1303
Folks- I have a helper class, the task of which is to build some messages based on the parameters. The class by itself does not have any private data (other than the instance ofcourse).
public class RequestBuilder {
private static RequestBuilder instance = new RequestBuilder();
private RequestBuilder() {}
public static RequestBuilder getInstance() {
return instance;
}
public SetRequest buildSetRequest(Path prefix,
Path path,
ConfigEntity configEntity,
Any protoAnyData) {
.....
.....
return setRequest;
}
public GetRequest buildGetRequest(Path prefix,
Path Path,
RetrieveRequestEntity retrieveRequestEntity,
Encoding encoding) {
.....
.....
return getRequest;
}
}
I understand singleton classes are not multithreading friendly. In this case, what happens when 2 threads try to execute buildSetRequest() at the same time?
Thanks for your time.
EDIT: Based on my need, and as suggested by @BoristheSpide in the comments below, I'm going to make this class as a utility class with the following changes: 1. Make it final. 2. Make methods static. 3. Remove all singleton references.
public final class RequestBuilder {
private RequestBuilder() {}
public static SetRequest buildSetRequest(Path prefix,
Path path,
ConfigEntity configEntity,
Any protoAnyData) {
.....
.....
return setRequest;
}
public static GetRequest buildGetRequest(Path prefix,
Path Path,
RetrieveRequestEntity retrieveRequestEntity,
Encoding encoding) {
.....
.....
return getRequest;
}
}
I'm leaving the original code as is, because it is still valid and gives context to the comments and answers to this question.
Upvotes: 1
Views: 1438
Reputation: 542
In this case, not too much, because your constructor is empty (what others mention as no shared state). Problems start when you have multiple private instance variables that you have to initialize. In that case, you need some protection like the doble-check:
private static volatile RequestBuilder instance;
private RequestBuilder() {}
public static RequestBuilder getInstance() {
if (instance == null) {
synchronized (RequestBuilder.class) {
if (instance == null) {
instance = new RequestBuilder();
}
}
}
return instance;
}
The reason is that a thread can be suspended at any time. If the current thread constructing the instance is suspended, and another one comes, there can be half initialized instance variables and the object can end up in a corrupted state.
EDIT: About buildSetRequest()
The code is inside a method, if this method create it's own instances itself or works with thread safe classes, there won't be any problem.
Upvotes: 1