Is a synchronized (this) {} block sufficient here?

I have lots of code which uses JAXB Marshaller and Unmarshaller class member objects (i.e. I create these in the constructor of a class and use them in several methods of the class). Unfortunately I've just found out that these two JAXB classes are not thread safe (see https://jaxb.dev.java.net/guide/Performance_and_thread_safety.html).

I'd prefer not to create these Marshaller and Unmarshaller objects each time I need them, so I wonder if I can get around the thread safety issue by just placing the marshal/unmarshal code in a synchronized block? Something like this:

// unmarshal the XML to an object

synchronized (this){

myObject = (MyObject) myObjectUnmarshaller.unmarshal(inputStream);

}

Is this the best way to go about this? If not then why not, and what's a better solution? Thanks in advance for your help.

--James

[1030 byte] By [monocongoa] at [2007-11-27 10:59:44]
# 1

You could consider synchronizing over the myObjectUnmarshaller :/

I don't know in what context you're going to use this code and neither do I know the costs of initialisation of your myObjectUnmarshaller. But if it is not time-critical and/or the costs of initialisation of a new instance are low then I would advice you not to avoid using these kind of constructs.

The preffered order of constructs is (at least that's what I think):

1. Are you sure more then one thread can acces an Object -instance? if you're sure it will not then you can leave the synchronized out.

2. If Multiple threads could access an Object-instance then wouldn't it be possible to somehow create a seperate Object-instance for each Thread.

3. If none of the above solves your problem then use your solution.

Lets suppose I have 20 incomming socket connections that all need some processing by an object called Processor. Imagine that each connection is handled by it's own thread. The call to the processor is like:

byte data[] = new byte[1000];

connection.read(data);

synchronized(this) {

processor.doProcess(data);

}

In this case we assume the processor is shared by all threads handling the connections. If all handlers would need the processor at the same moment, they all would have to wait in a line to run.

Instead we could give each handler it's own processor and we would have no waiting line.

BTW the link proposes creating a pool (this one should be between point 2 and 3) ... maybe that's an option ?

DikkeDouwea at 2007-7-29 12:25:09 > top of Java-index,Core,Core APIs...