001 /* 002 * Copyright (c) 2007-2014 Concurrent, Inc. All Rights Reserved. 003 * 004 * Project and contact information: http://www.cascading.org/ 005 * 006 * This file is part of the Cascading project. 007 * 008 * Licensed under the Apache License, Version 2.0 (the "License"); 009 * you may not use this file except in compliance with the License. 010 * You may obtain a copy of the License at 011 * 012 * http://www.apache.org/licenses/LICENSE-2.0 013 * 014 * Unless required by applicable law or agreed to in writing, software 015 * distributed under the License is distributed on an "AS IS" BASIS, 016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 017 * See the License for the specific language governing permissions and 018 * limitations under the License. 019 */ 020 021 package cascading.flow.stream; 022 023 import java.util.concurrent.atomic.AtomicInteger; 024 025 import cascading.flow.FlowElement; 026 import cascading.flow.FlowProcess; 027 import cascading.tuple.TupleEntry; 028 029 /** 030 * 031 */ 032 public class MergeStage extends ElementStage<TupleEntry, TupleEntry> implements Collapsing 033 { 034 private boolean started = false; 035 protected final AtomicInteger completeCount = new AtomicInteger( 0 ); 036 private int numIncomingPaths; 037 038 public MergeStage( FlowProcess flowProcess, FlowElement flowElement ) 039 { 040 super( flowProcess, flowElement ); 041 } 042 043 @Override 044 public void bind( StreamGraph streamGraph ) 045 { 046 super.bind( streamGraph ); 047 048 numIncomingPaths = streamGraph.countAllEventingPathsTo( this ); 049 } 050 051 @Override 052 public void initialize() 053 { 054 super.initialize(); 055 056 completeCount.set( numIncomingPaths ); 057 } 058 059 @Override 060 public synchronized void start( Duct previous ) 061 { 062 if( started ) 063 return; 064 065 super.start( previous ); 066 started = true; 067 } 068 069 @Override 070 public void complete( Duct previous ) 071 { 072 if( completeCount.decrementAndGet() != 0 ) 073 return; 074 075 super.complete( previous ); 076 completeCount.set( numIncomingPaths ); 077 } 078 }