001/*
002 * Copyright (c) 2007-2017 Xplenty, 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
021package cascading.flow.stream.element;
022
023import java.util.concurrent.atomic.AtomicInteger;
024
025import cascading.flow.FlowElement;
026import cascading.flow.FlowProcess;
027import cascading.flow.stream.duct.Collapsing;
028import cascading.flow.stream.duct.Duct;
029import cascading.flow.stream.graph.StreamGraph;
030import cascading.tuple.TupleEntry;
031
032/**
033 *
034 */
035public class MergeStage extends ElementStage<TupleEntry, TupleEntry> implements Collapsing
036  {
037  private boolean started = false;
038  protected final AtomicInteger completeCount = new AtomicInteger( 0 );
039  private int numIncomingPaths;
040
041  public MergeStage( FlowProcess flowProcess, FlowElement flowElement )
042    {
043    super( flowProcess, flowElement );
044    }
045
046  @Override
047  public void bind( StreamGraph streamGraph )
048    {
049    super.bind( streamGraph );
050
051    numIncomingPaths = streamGraph.findAllPreviousFor( this ).length;
052    }
053
054  @Override
055  public void initialize()
056    {
057    super.initialize();
058
059    completeCount.set( numIncomingPaths );
060    }
061
062  @Override
063  public synchronized void start( Duct previous )
064    {
065    if( started )
066      return;
067
068    super.start( previous );
069    started = true;
070    }
071
072  @Override
073  public void complete( Duct previous )
074    {
075    if( completeCount.decrementAndGet() != 0 )
076      return;
077
078    super.complete( previous );
079    completeCount.set( numIncomingPaths );
080    }
081  }