Re: synchronization and context switch between thread
On 4/21/2010 8:43 PM, markspace wrote:
Ubuntu guy wrote:
Ok got it, thanks for the quick response. I'm suspecting a starvation
of thread2 (as in whenever it gets a chance to execute, the lock is
held by thread1 and whenever thread1 releases the lock the CPU is not
context switching to thread2). Is there any smart way to avoid if this
is the case?
You might try a re-entrant lock which is explicitly fair. Please let us
know how this works, I've never tried it when the contention was high
enough to actually cause detectable starvation.
<http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html>
Note I think you'll have to use the Reentrant(true) constructor to get
the fair scheduling behavior.
Good advice, but keep in mind that fair locks are generally less
performant than unfair locks. If you find that your thread is starving,
then you should consider switching to fair locks. However, in many cases
this isn't actually a problem to have unfair locks.
Something else to consider, try restructuring your code so that as much
as possible is outside of the synchronization block. Look into using
CAS (Compare and swap) based algorithms where applicable.
Often, the goal of using synchronized() is to make an operation atomic.
There are many other approaches to making atomic operations which
don't cause such a strong serialization of actions.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>