This is a helper class and sample how to use synchronization for simultaneous read and blocked  writing in java.
There are Sources and JavaDoc .

This source had being written as an answer on professional  interview.
Code never being tested and if You have any comments, or used it, please e-mail me about.


In proposed case we are assuming long read operation, so double lock-unlock expenses can be ignored. If reading process is enough short, simple synchronization by this object can be much sufficient.
Sample how to use RwSync class:
try
{
	RwSync sem = new RwSync();
	/////////////////////////////////
	// read access sample
	try
	{	sem.ReadLock();
		// do reading
	}finally
	{	sem.ReadUnlock();
	}

       	/////////////////////////////////
	// write access sample
	synchronized( sem )
	{	sem.WriteAcquire();
		// write operation
	}
}catch( Exception e )
	{   e.printStackTrace();	}


FYI. Entities, responsible for synchronization in java:
synchronized keyword in metod declaration. Used to prevent simultanious access for object data members and methods.
Same as synchronized( this ) inside of method.
class Foo
{
public syncronized void aMethod()
{
// ...
}
}
synchronized(obj) statement in block Lock access to object in scope of block
class Foo 
{ Object sync=new Object();
void aMethod()
{
synchronized( sync )
{
// ...
}
}
object.wait([milis[,nanos]])
methods in java.lang.Object
( parent for any object )

Stops current thread execution until notify() or notifyAll() will be called by another thread.
class Foo 
{ Object sync=new Object();
void aMethod()
{ // exception handler not shown
synchronized( sync )
{ sync.wait();
// ...
}
}
}
object.notify()
object.notifyAll()

methods in java.lang.Object Release threads, waiting for notification.
class Foo 
{ Object sync=new Object();
void aMethod()
{
synchronized( sync )
{ // some locked processing..
sync.notifyAll();
}
}
static initializators
static variable initialization or static block
Lock access to class-scope variables
class Foo 
{
static Object gblSync=new Object();
// static initializator locks class
static
{ // this block locks class ...
}
}
Detailed definitions can be found in The Java Language Specification.



© 2003 Oleksandr Firsov