thread problem - any ideas here?

J

Jamie

Hi there,

I have several threads (2..n) that need to execute a block of code
(for discussion sake, call this "A"), and only one thread (1) that
needs to execute a block of code "B". Now, threads (2..n) must be able
to execute A simultaneously, however, they may not do so while thread
(1) is executing block of code "B". Thread (1) can only execute block
of code "B" when threads (2..n) are not executing block of code "A".
The precise number of threads is unknown. How does one achieve this in
Java? The below code will not work because the synchronized(mutex)
statement will mean that threads (1..n) can execute block of code A
simultaneously. Right?

class Example
{
Object mutex;

class Threads2toN implements Runnable
{
public run()
{
synchronized(mutex) {
//block of code A;
}

}
}

class Thread1
{
public run() {
synchronized(mutex) {
// block of code B;
}
}
}
 
F

Ferenc Hechler

Hi Jamie,

you can use a counter, how many threads are currently executing block A.
the counter may be locked by Thread2ToN only for short, when it is increased
or decreased.
Thread1 locks the counter the whole time while processing block B, so no
other thread
can increase the counter while executing block B.

Thread2ToN may send a notify for any waiting Therad1 if counter reaches 0.

The code might look something like that:

class Example
{
Object mutex;
int counter = 0;

class Threads2toN implements Runnable
{
public run()
{
synchronized(mutex) {
counter += 1;
}
//block of code A;
synchronized(mutex) {
counter -= 1;
if (counter == 0) {
mutex.notify();
}
}
}
}

class Thread1
{
public run() {
synchronized(mutex) {
while (count > 0) {
mutex.wait();
}
// block of code B;
}
}
}
 
S

shakah

Would a read/write lock (one writer, many readers) abstraction work
here? If B obtains the lock for writing it would block the A threads,
and it would allow multiple A threads to execute otherwise.

Though I don't think Java has a RWLock, googling for "Java read write
mutex" yields a few promising-looking links, e.g.
http://www.asingh.net/technical/rwlocks.html.
 
C

Chris Uppal

shakah said:
Though I don't think Java has a RWLock

They have just been added in 1.5.0 as part of the new concurrency package. For
instance, java.util.concurrent.locks.ReentrantReadWriteLock.

-- chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top