Samstag, 29. November 2008

EE3206/EE5805 Java thread-4

EE3206/EE5805 Java Programming and application

notes on 14.3.1 Synchronized methods
excerpted from the "The Java Programming Language, 4th ed."

1. Synchronization forces execution of the two threads to be mutually exclusive in time. On the contrary, unsynchronized access does not wait for any locks but proceeds regardless of locks that may be held on the object.

2. Locks are owned per thread, so invoking a synchronized method from within another method synchronized on the same object will proceed without blocking, releasing the lock only when the outermost synchronized method returns.

3. This per-thread behavior prevents a thread from blocking on lock it already has, and permits recursive method invocations and invocations of inherited methods which themselves may be synchronized.

4. The constructor does not need to be synchronized because it is executed only when creating an object, and that can happen in only one thread for any given new object.

5. Access to the field must be synchronized. With the synchronized declaration, two or more running thread are guaranteed not to interfere with each other.

6. There is no guarantee as to the order of operations. If the balance is queried about the same time that a deposit occurs, one of them will complete first but you cannot tell which.

7. You can ask whether the current thread holds the lock on a given object by passing that object to the Thread class's static holdsLock() method, which returnstrue if the current thread does hold the lock on that object.

Eg. assert Thread.holdsLock(this);

8. When an extended class overrides a synchronized method, the new method can be synchronized or not. The superclass's method will still be synchronized when it is invoked.

9. If the unsynchronized method uses super to invoke the superclss's synchronized method, the object 's lock will be acquired at that time and will be released when the superclass's method returns.




Keine Kommentare: