Re: understanding: synchronized reference



On 09.08.2006 13:00, John_Woo wrote:
Hi,

I want some classification on understanding the context of synchronized
reference:

say

LinkedList queue = new LinkedList();

public Object pop() throws InterruptedException {
synchronized(queue) {
while (queue.isEmpty()) {
queue.wait();
}
return queue.removeFirst();
}
}

public void put(Object o){queue.add(o);}

public void do(){
pup();
put(o);
put(o);
pup();
..
}

case 1:pop never called
case 2: pop called only once
cass 3: pop/put called many times

I'm wondering, in above 3 cases, what happened to queue in terms of
synchronization?
like,
in case 1, is it queue not synchronized?
in case 2, if queue size always > 0 ; queue not synchronized?

The question doesn't really make sense to me. It reads as if "synchronizing" does something to the queue content which it does not. Synchronizing ensures exclusive access to a lock for a single thread.

If queue should be accessed from multiple threads access needs to be synchronized. Note, that in Java 1.5 there is are queue classes that has proper synchronization built in. See here for example

http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html

when queue is synchronized in pop, did that imply it synchronized
anywhere in same class?

No. But it must be synchronized in put. Also, put must invoke queue.notifyAll() to make pop() wake up.

Kind regards

robert
.



Relevant Pages

  • Re: Network Stack Locking
    ... coallescing of context switches to process multiple packets. ... therefore effective coallescing of synchronization. ... for example, if your stack trace in the ... TCP code only goes up to the queue receive primitive, ...
    (freebsd-arch)
  • Re: pthread_cond_wait and pthread_cond_signal
    ... I have a thread A that initialy finds a queue empty and therefore calls ... Why does it not wake up after T1 calls pthread_cond_signal?? ... You are inferring SCHEDULING based on SYNCHRONIZATION operations, and that's not what you should expect or what you should want. ... But one possible legitimate sequence of operations is this: you create 4 threads that will each immediately lock the mutex. ...
    (comp.programming.threads)
  • understanding: synchronized reference
    ... LinkedList queue = new LinkedList; ... public Object popthrows InterruptedException { ... public void put ...
    (comp.lang.java.programmer)
  • Re: NPE in PriorityQueue.poll()
    ... vulnerable to synchronization problems. ... It's definitely synchronizing on the queue every time ... it accesses it. ... only a proper reference or an exception; ...
    (comp.lang.java.programmer)
  • Re: A signal race condition
    ... > other writing message onto the message queue. ... you are using shared memory? ... is that the synchronization mechnism is ...
    (comp.unix.programmer)