KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > prevayler > implementation > publishing > POBox


1 //Prevayler(TM) - The Free-Software Prevalence Layer.
2
//Copyright (C) 2001-2003 Klaus Wuestefeld
3
//This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
4
//Contributions: Frederic Langlet
5

6 package org.prevayler.implementation.publishing;
7
8 import java.util.Date JavaDoc;
9 import java.util.LinkedList JavaDoc;
10
11 import org.prevayler.Transaction;
12 import org.prevayler.implementation.TransactionTimestamp;
13
14
15 /** An assyncronous buffer for transaction subscribers.
16  */

17 public class POBox extends Thread JavaDoc implements TransactionSubscriber {
18     
19     private final LinkedList JavaDoc _queue = new LinkedList JavaDoc();
20     private final TransactionSubscriber _delegate;
21   
22
23     public POBox(TransactionSubscriber delegate) {
24         _delegate = delegate;
25         setDaemon(true);
26         start();
27     }
28
29
30     public synchronized void receive(Transaction transaction, Date JavaDoc timestamp) {
31         _queue.add(new TransactionTimestamp(transaction, timestamp));
32         notify();
33     }
34
35
36     public void run() {
37         while (true) {
38             TransactionTimestamp notification = waitForNotification();
39             _delegate.receive(notification.transaction(), notification.timestamp());
40         }
41     }
42
43
44     private synchronized TransactionTimestamp waitForNotification() {
45             while (_queue.size() == 0) waitWithoutInterruptions();
46             return (TransactionTimestamp)_queue.removeFirst();
47     }
48
49
50     private void waitWithoutInterruptions() {
51         try {
52             wait();
53         } catch (InterruptedException JavaDoc e) {
54             throw new RuntimeException JavaDoc("Unexpected InterruptedException.");
55         }
56     }
57
58 }
Popular Tags