001/* 002 * (C) Copyright 2017 Nuxeo (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Florent Guillaume 018 */ 019package org.nuxeo.runtime.pubsub; 020 021import org.apache.commons.logging.Log; 022import org.apache.commons.logging.LogFactory; 023 024/** 025 * Encapsulates invalidations management through the {@link PubSubService}. 026 * 027 * @since 9.3 028 */ 029public abstract class AbstractPubSubInvalidationsAccumulator<T extends SerializableAccumulableInvalidations> 030 extends AbstractPubSubBroker<T> { 031 032 private static final Log log = LogFactory.getLog(AbstractPubSubInvalidationsAccumulator.class); 033 034 protected volatile T bufferedInvalidations; 035 036 /** Constructs new empty invalidations, of type {@link T}. */ 037 public abstract T newInvalidations(); 038 039 @Override 040 public void initialize(String topic, String discriminator) { 041 bufferedInvalidations = newInvalidations(); 042 super.initialize(topic, discriminator); 043 } 044 045 @Override 046 public void close() { 047 super.close(); 048 // not null to avoid crashing subscriber thread still in flight 049 bufferedInvalidations = newInvalidations(); 050 } 051 052 /** 053 * Sends invalidations to other nodes. 054 */ 055 public void sendInvalidations(T invalidations) { 056 sendMessage(invalidations); 057 } 058 059 @Override 060 public void receivedMessage(T invalidations) { 061 if (log.isTraceEnabled()) { 062 log.trace("Received invalidations: " + invalidations); 063 } 064 synchronized (this) { 065 bufferedInvalidations.add(invalidations); 066 } 067 } 068 069 /** 070 * Receives invalidations from other nodes. 071 */ 072 public T receiveInvalidations() { 073 T newInvalidations = newInvalidations(); 074 T invalidations; 075 synchronized (this) { 076 invalidations = bufferedInvalidations; 077 bufferedInvalidations = newInvalidations; 078 } 079 if (log.isTraceEnabled()) { 080 log.trace("Received invalidations: " + invalidations); 081 } 082 return invalidations; 083 } 084 085}