How do I use the Java API in a Thread-Safe Manner?



How do I use the Java API in a Thread-Safe Manner?

Hello,

I am writing a Java servlet and am new to coding for thread synchronization.
I suspect that there must be an "obvious" solution to the following problem
but after sevearl days of research I can't find it!

It is my understanding that, in general, the J2SE 1.4 API is *not*
thread-safe. There are some APIs where the Sun documentation states that a
Class's methods are thread-safe (such as StringBuffer) but in general, most
of the text and web search references I have found have stated that the API
in general is not thread-safe. That means that there must be at least one
(and it's probably most) API that is not thread-safe and let me just call
such an unsafe method "UnsafeAPI()". My question is, how do I use
UnsafeAPI() and write code to make my code thread-safe?

For example, if I have the following code:

public final class MyClass {
private int i;
private int j;
private int k;

public finale void MyMethod(int i, int j, int k)
{
this.i = i;
this.j = j;
this.k = k;
}
}

I have a thread safety issue here. Assignement to an int is atomic so no
one of the three assignment statements in MyMethod() can be interrupted by
another thread. However, the *sequence of all three assignments* certainly
can be interrupted so I am vulnerable to a synchronization issue. I could
either fix this proiblem by adding the "sychronized" modifier to the
MyMethod declaration, or I could do the following:


public final class MyClass {
private int i;
private int j;
private int k;

public finale void MyMethod(int i, int j, int k)
{
synchronize(this) {
this.i = i;
this.j = j;
this.k = k;
}
}
}

At this point I am thread safe. However, assume that I also need to call
UnsafeAPI(). Now my code looks like:

public final class MyClass {
private int i;
private int j;
private int k;

public finale void MyMethod(int i, int j, int k)
{
synchronize(this) {
this.i = i;
this.j = j;
this.k = k;
UnsafeAPI(); // this is any J2SE 1.4 API that, in general, is not
thread safe!
}
}
}

The synchronize(this) guarantees that no other thread can enter *my code
block* in MyMethod() but (as far as I can tell) it in no way prevents
another thread from entering UnsafeAPI() from another block of code, either
in my servlet or even in another application altogether.

There must be some way to block a thread from entering UnsafeAPI() because
otherwise it would be impossible to write a thread safe application, but I
sure can't find a way to do this. Can someone explain how this is done? If
you can also tell me how/where you learned how to do this I would be very
interested because I can't locate any such information!)

Thank you!
Al

AlKoch@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


.



Relevant Pages