I want that only one instance of my class, Format1 should be returned through the class Engine:
public final class Engine {
private static Format format;
public Engine(final Param1 param1, final Param2 param2) {
Engine.format = new FormatV1(param1); // FormatV1 implements Format
}
static Format getFormat(int condition) {
switch(condition) {
case 1 : return format;
}
}
}
Does this ensure that only one and correct instance of Format is returned via getFormat?
Also, the client which invokes the getFormat() needs to execute method on the format object (which has absolutely no state) but passes a ByteBuffer to the method (this ByteBuffer might be modified):
class Client
{
public static void main(String[] args) {
Format obj = Engine.getFormat(1); // some param
ByteBuffer buffer; // read data from disk
synchronized (obj) {
long[] result = obj.method(buffer);
if (result == null) {
// do something
}
}
}
}
Does the synchronized construct here/like this ensure serializability ?
P.S: I'm very new to Java, as much as I read I could also make the method synchronized but I think the check (result == null) should also be included in the critical section so I decided to use the synchronized (obj) construct instead. Please forgive me if this is a silly question but I want to confirm my doubts.