2005/5/9

     
 

Synchronization

artefaktur

| References | Casting | Arrays | Import | instanceof | Package | Synchronization | Throwable | finally | Dangerous | Stack | String |

In Java and ACDK, synchronization is handled via the Object instance.

In Java, you can synchronize the access to Objects with the 'synchronized' keyword:

// Java
class Foo
public Object
{
  int _counter;

  public synchronized int foo()
  {
    return ++_counter;
  }
}
In ACDK, the same is shown in the following way:

// C++ / acdk
class Foo
: public Object
{
  int _counter;

public:

  virtual int foo()
  {
    SYNCHRONIZETHIS();
    return ++_counter;
  }
};
The same will be received except with (exception handling), if you declare to do the following:

// Java / acdk
int foo()
{
  lock();
  int retval = ++_counter;
  unlock();
  return retval;
}
This usage is usually not recommended, since an exception between lock() and unlock() leaves the Object locked.
(See also  Finally)

An alternative usage of synchronization in Java is:

// Java
void foo(Object obj2lock)
{
  synchronized(obj2lock) { // or: obj2lock.lock();
  } // or: obj2lock.unlock();
}
In acdk it looks like:

// C++ / acdk
void foo(RObject obj2lock)
{
  {
    SYNCHRONIZEOBJECT(obj2lock)  // or: obj2lock->lock();
  } // or: obj2lock->unlock();
}
Please notice the different possition at the beginning of the block before declaring SYNCHRONIZEOBJECT(obj2lock).


 < prevConstructs(7 / 12) next >