Thursday, March 3, 2011

Thread Safety

1 .All threads inside a Java virtual machine (JVM) share the same heap and method area
2. Because multithreading is built into Java, it is possible that any class you design eventually may be used concurrently by multiple threads.

Given the architecture of the JVM, you need only be concerned with instance and class variables when you worry about thread safety. Because all threads share the same heap, and the heap is where all instance variables are stored,

You needn't worry about multithreaded access to local variables, method parameters, and return values, because these variables reside on the Java stack. In the JVM, each thread is awarded its own Java stack. No thread can see or use any local variables, return values, or parameters belonging to another thread.

Given the structure of the JVM, local variables, method parameters, and return values are inherently "thread-safe." But instance variables and class variables will only be thread-safe if you design your class appropriately.

Three ways to make an object thread-
Synchronize critical sections
public void setColor(int r, int g, int b) {
checkRGBVals(r, g, b);
synchronized (this) {
this.a = r
this.b = g
}
}

public synchronized void invert() {
r = 255 - r;
g = 255 - g;
b = 255 - b;
}

Make it immutable

public RGBColor invert() {
RGBColor retVal = new RGBColor(255 - r,
255 - g, 255 - b);
return retVal;
}

Use a thread-safe wrapper

http://www.artima.com/designtechniques/threadsafety7.html

The third approach to making an object thread-safe is to embed that object in a thread-safe wrapper object. In this approach you leave the original class (which isn't thread-safe) unchanged and create a separate class that is thread-safe.

-------------
thread safety may involve a performance penalty
Synchronized method invocations generally are going to be slower than non-synchronized method invocations.

Synchronized method invocations generally are going to be slower than non-synchronized method invocations.

Unnecessary synchronized method invocations (and synchronized blocks) can cause unnecessary blocking and unblocking of threads, which can hurt performance.

Immutable objects tend to be instantiated more often, leading to greater numbers of often short-lived objects that can increase the work of the garbage collector.

Synchronization gives rise to the possibility of deadlock, a severe performance problem in which your program appears to hang.

No comments:

Post a Comment