Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • teetime/teetime
  • nts/teetime
  • mne/teetime
3 results
Show changes
Showing
with 895 additions and 49 deletions
/**
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package teetime.framework.divideandconquer;
import java.util.concurrent.atomic.AtomicInteger;
/**
* An object with an unique ID.
*
* @author Robin Mohr
*
*/
public class Identifiable {
private static final AtomicInteger ID_GENERATOR = new AtomicInteger();
private final int identifier;
protected Identifiable() {
this.identifier = ID_GENERATOR.incrementAndGet();
}
protected Identifiable(final int newID) {
this.identifier = newID;
}
public int getID() {
return this.identifier;
}
}
/**
* Copyright (C) 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime.sourceforge.net)
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
......@@ -15,14 +15,19 @@
*/
package teetime.framework.exceptionHandling;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import teetime.framework.Stage;
import teetime.framework.AbstractStage;
/**
* Represent a minimalistic StageExceptionListener. Listener which extend from this one, must a least implement this functionality.
* This abstract class provides a Logger {@link #logger} and a method to terminate the threads execution {@link #terminateExecution()}.
* Represents a minimalistic StageExceptionListener.
* Listener which extend from this one, must a least implement this functionality.
* This abstract class provides a Logger {@link #logger} and the method {@link #onStageException(Exception, AbstractStage)} which is called on every raised
* exception.
*/
public abstract class AbstractExceptionListener {
......@@ -30,25 +35,38 @@ public abstract class AbstractExceptionListener {
CONTINUE, TERMINATE
}
/**
* The default logger, which can be used by all subclasses
*/
protected final Logger logger;
/** The default logger, which can be used by all subclasses */
protected final Logger logger; // NOPMD can't be static as it needs to be initialized in cstr
private final List<Exception> loggedExceptions = new ArrayList<Exception>();
private final boolean logExceptions;
public AbstractExceptionListener() {
protected AbstractExceptionListener(final boolean shouldLogExceptions) {
this.logger = LoggerFactory.getLogger(this.getClass().getCanonicalName());
this.logExceptions = shouldLogExceptions;
}
/**
* This method will be executed if an exception arises.
*
* @param e
* @param exception
* thrown exception
* @param throwingStage
* the stage, which has thrown the exception.
* @return
* true, if the thread should be terminated, false otherwise
* true, if the thread should be terminated, false otherwise
*/
public abstract FurtherExecution onStageException(Exception e, Stage throwingStage);
public abstract FurtherExecution onStageException(Exception exception, AbstractStage throwingStage);
public List<Exception> getLoggedExceptions() {
return loggedExceptions;
}
public FurtherExecution reportException(final Exception e, final AbstractStage stage) {
if (logExceptions) {
loggedExceptions.add(e);
}
return onStageException(e, stage);
}
}
/**
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package teetime.framework.exceptionHandling;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public abstract class AbstractExceptionListenerFactory<T extends AbstractExceptionListener> {
private final Map<Thread, List<Exception>> threadExceptionsMap = new ConcurrentHashMap<Thread, List<Exception>>();
protected abstract T createInstance();
public T createInstance(final Thread thread) {
T instance = createInstance();
threadExceptionsMap.put(thread, instance.getLoggedExceptions());
return instance;
}
public Map<Thread, List<Exception>> getThreadExceptionsMap() {
return threadExceptionsMap;
}
}
/**
* Copyright (C) 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime.sourceforge.net)
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
......@@ -15,12 +15,16 @@
*/
package teetime.framework.exceptionHandling;
import teetime.framework.Stage;
import teetime.framework.AbstractStage;
class IgnoringExceptionListener extends AbstractExceptionListener {
IgnoringExceptionListener() {
super(false);
}
@Override
public FurtherExecution onStageException(final Exception e, final Stage throwingStage) {
public FurtherExecution onStageException(final Exception exception, final AbstractStage throwingStage) {
return FurtherExecution.CONTINUE;
}
}
/**
* Copyright (C) 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime.sourceforge.net)
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
......@@ -15,10 +15,10 @@
*/
package teetime.framework.exceptionHandling;
public class IgnoringExceptionListenerFactory implements IExceptionListenerFactory {
public class IgnoringExceptionListenerFactory extends AbstractExceptionListenerFactory<IgnoringExceptionListener> {
@Override
public AbstractExceptionListener createInstance() {
protected final IgnoringExceptionListener createInstance() {
return new IgnoringExceptionListener();
}
......
/**
* Copyright (C) 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime.sourceforge.net)
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
......@@ -15,13 +15,19 @@
*/
package teetime.framework.exceptionHandling;
import teetime.framework.Stage;
import teetime.framework.AbstractStage;
class LoggingExceptionListener extends AbstractExceptionListener {
LoggingExceptionListener() {
super(true);
}
@Override
public FurtherExecution onStageException(final Exception e, final Stage throwingStage) {
logger.warn("Exception occurred in " + throwingStage.getId(), e);
public FurtherExecution onStageException(final Exception exception, final AbstractStage throwingStage) {
if (logger.isWarnEnabled()) {
logger.warn("Exception occurred in " + throwingStage.getId(), exception);
}
return FurtherExecution.CONTINUE;
}
......
/**
* Copyright (C) 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime.sourceforge.net)
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
......@@ -15,10 +15,10 @@
*/
package teetime.framework.exceptionHandling;
public class LoggingExceptionListenerFactory implements IExceptionListenerFactory {
public class LoggingExceptionListenerFactory extends AbstractExceptionListenerFactory<LoggingExceptionListener> {
@Override
public AbstractExceptionListener createInstance() {
protected final LoggingExceptionListener createInstance() {
return new LoggingExceptionListener();
}
......
/**
* Copyright (C) 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime.sourceforge.net)
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
......@@ -15,24 +15,24 @@
*/
package teetime.framework.exceptionHandling;
import teetime.framework.Stage;
import teetime.util.StacklessException;
public class TestListener extends AbstractExceptionListener {
/**
* Represents an exception which is used to terminate the running thread.
*
* @since 1.1
*/
public final class TerminateException extends StacklessException {
public static int exceptionInvoked = 0;
public static final TerminateException INSTANCE = new TerminateException("Framework Exception");
public TestListener() {
TestListener.exceptionInvoked = 0;
}
/**
* Generated UID
*/
private static final long serialVersionUID = 6724637605943897808L;
@Override
public FurtherExecution onStageException(final Exception e, final Stage throwingStage) {
exceptionInvoked++;
if (exceptionInvoked == 2) {
return FurtherExecution.TERMINATE;
} else {
return FurtherExecution.CONTINUE;
}
private TerminateException(final String string) {
super(string);
}
}
/**
* Copyright (C) 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime.sourceforge.net)
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
......@@ -15,14 +15,26 @@
*/
package teetime.framework.exceptionHandling;
import teetime.framework.Stage;
import java.util.List;
import teetime.framework.AbstractStage;
class TerminatingExceptionListener extends AbstractExceptionListener {
TerminatingExceptionListener() {
super(true);
}
@Override
public FurtherExecution onStageException(final Exception e, final Stage throwingStage) {
logger.warn("Exception occurred in " + throwingStage.getId(), e);
public FurtherExecution onStageException(final Exception exception, final AbstractStage throwingStage) {
if (logger.isWarnEnabled()) {
logger.warn("Exception occurred in " + throwingStage.getId(), exception);
}
return FurtherExecution.TERMINATE;
}
public List<Exception> getExceptions() {
return getLoggedExceptions();
}
}
/**
* Copyright (C) 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime.sourceforge.net)
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
......@@ -15,10 +15,10 @@
*/
package teetime.framework.exceptionHandling;
public class TerminatingExceptionListenerFactory implements IExceptionListenerFactory {
public class TerminatingExceptionListenerFactory extends AbstractExceptionListenerFactory<TerminatingExceptionListener> {
@Override
public AbstractExceptionListener createInstance() {
public TerminatingExceptionListener createInstance() {
return new TerminatingExceptionListener();
}
......
/**
* Copyright (C) 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime.sourceforge.net)
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
......@@ -14,9 +14,9 @@
* limitations under the License.
*/
package teetime.framework.exceptionHandling;
public interface IExceptionListenerFactory {
public AbstractExceptionListener createInstance();
}
/**
* TODO:
*
*
*
*/
/**
* Copyright (C) 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime.sourceforge.net)
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
......
/**
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package teetime.framework.performancelogging;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import teetime.framework.AbstractStage;
import teetime.framework.performancelogging.formatstrategy.CumulativeActivePassivTime;
/**
* This class serves as storage for information about active and inactive times of objects.
*
* @author Adrian
*
*/
public class ActivationStateLogger {
/**
* Singleton Instance Holder
*/
private static final ActivationStateLogger INSTANCE = new ActivationStateLogger();
/**
* Set of registered Stages
*/
private final Set<AbstractStage> stages = new LinkedHashSet<AbstractStage>();
/**
* An Integer that holds the longest of all registered simple Stage names.
*/
private int longestName = 0;
private IFormatingStrategy formatingStrategy = new CumulativeActivePassivTime(stages);
private ActivationStateLogger() {
// singleton
}
public static ActivationStateLogger getInstance() {
return ActivationStateLogger.INSTANCE;
}
/**
* Any stage can register itself here. It will be stored with an empty List of States.
*
* @param stage
* Stage to be registered.
*/
public void register(final AbstractStage stage) {
this.setLongestName(stage.getClass().getSimpleName().length());
stages.add(stage);
}
public void logToFile() throws UnsupportedEncodingException, FileNotFoundException {
this.logToFile("StateLogs/");
}
public void logToFile(final String path) throws UnsupportedEncodingException, FileNotFoundException {
Calendar now = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat();
String date = formatter.format(now.getTime()).replace('.', '-').replace(':', '.').replace(' ', '_');
String filename = "StateLog_" + date + ".txt";
this.logToFile(path, filename);
}
public void logToFile(final String path, final String filename) throws UnsupportedEncodingException, FileNotFoundException {
this.logToFile(new File(path + filename));
}
public void logToFile(final File file) throws UnsupportedEncodingException, FileNotFoundException {
try {
this.printToFile(file);
} catch (FileNotFoundException e) {
try {
if (file.createNewFile()) {
this.printToFile(file);
} else {
System.err.println("File wasn't created!");
}
} catch (IOException ioe) {
System.err.println("Error creating " + file.toString());
}
}
}
private void printToFile(final File file) throws UnsupportedEncodingException, FileNotFoundException {
PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(file, true), 8192 * 8), false, "UTF-8");
ps.print(this);
ps.close();
System.out.println("Log saved to File: " + file.getAbsolutePath());
}
// getter and setter:
public Set<AbstractStage> getStages() {
return stages;
}
public int getLongestName() {
return longestName;
}
public void setLongestName(final int longestName) {
if (longestName > this.longestName) {
this.longestName = longestName;
}
}
public IFormatingStrategy getFormatingStrategy() {
return formatingStrategy;
}
public void setFormatingStrategy(final IFormatingStrategy formatingStrategy) {
this.formatingStrategy = formatingStrategy;
}
// toString and inner classes
@Override
public String toString() {
String result = "";
result += this.formatingStrategy.formatData();
return result;
}
public interface IFormatingStrategy {
public String formatData();
}
}
/**
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package teetime.framework.performancelogging;
public interface CompositeStateLoggable {
public void registerStatebles();
}
/**
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package teetime.framework.performancelogging;
/**
* This class stores an active/inactive flag at a given time.
*
* @author Adrian
*
*/
public class StateChange {
public enum StageActivationState {
/**
* Represents the state where the stage has been initialized, but not yet been executed.
* This state is used to implement the null object pattern.
* It avoids to check for <code>this.lastState == null</code>.
*/
INITIALIZED,
/** Represents the state where the stage is being executed. */
ACTIVE,
/** Represents the state where the stage is waiting for its passive successor stage to return. */
// ACTIVE_WAITING,
/** Represents the state where the stage is waiting for its active successor stage to consume the elements within the interconnected pipe. */
BLOCKED,
/** Represents the stage where the stage has been terminated. */
TERMINATED,
}
private final StageActivationState stageActivationState;
private final long timeStamp;
public StateChange(final StageActivationState state, final long timeStamp) {
this.stageActivationState = state;
this.timeStamp = timeStamp;
}
public StageActivationState getStageActivationState() {
return stageActivationState;
}
public long getTimeStamp() {
return timeStamp;
}
}
/**
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package teetime.framework.performancelogging.formatstrategy;
import java.util.Collection;
import teetime.framework.AbstractStage;
import teetime.framework.StateStatistics;
import teetime.framework.performancelogging.ActivationStateLogger.IFormatingStrategy;
import teetime.framework.performancelogging.StateChange;
import teetime.framework.performancelogging.StateChange.StageActivationState;
public class CumulativeActivePassivTime implements IFormatingStrategy {
private final Collection<AbstractStage> stages;
public CumulativeActivePassivTime(final Collection<AbstractStage> stages) {
this.stages = stages;
}
/**
* Will return the simple name of the given stage and added enough spaces to match the longest name.
*
* @param stage
* Stage which name should be formated.
* @return Simple name of the given stage plus spaces to match the longest name.
*/
String formateName(final AbstractStage stage) {
return stage.getClass().getSimpleName() + ";";
}
@Override
public String formatData() {
String result = "\n Formating to analyse differences in runtime:\n\n";
result += "name;total time;cumulative blocked time;cumulative active waiting time time;active time\n";
// go through all the stages
for (AbstractStage stage : stages) {
// first add a formated version of their names to the line.
result += formateName(stage);
long earliestTimeStamp = Long.MAX_VALUE;
long latestTimeStamp = Long.MIN_VALUE;
long lastTimeStamp = 0;
StageActivationState lastState = StageActivationState.INITIALIZED;
long cumulativeActiveTime = 0;
long cumulativeActiveWaitingTime = StateStatistics.getActiveWaitingTime(stage);
long cumulativeBlockedTime = 0;
// go through all states of this stage and sum up the active times while counting the number of active timestamp
for (StateChange state : StateStatistics.getStates(stage)) {
long actualTimeStamp = state.getTimeStamp();
// update earliest and latest timeStamp if necessary
if (actualTimeStamp < earliestTimeStamp) {
earliestTimeStamp = actualTimeStamp;
} else if (actualTimeStamp > latestTimeStamp) {
latestTimeStamp = actualTimeStamp;
}
// In the first loop neither lastTimeStamp nor lastState are set. So the next part wouldn't calculate correct.
if (lastState != StageActivationState.INITIALIZED) {
long elapsedTime = actualTimeStamp - lastTimeStamp;
switch (lastState) {
case ACTIVE:
cumulativeActiveTime += elapsedTime;
break;
case BLOCKED:
cumulativeBlockedTime += elapsedTime;
break;
case TERMINATED:
break;
default:
break;
}
}
lastTimeStamp = actualTimeStamp;
lastState = state.getStageActivationState();
}
// The ActiveWaiting time was counted into active time till now. So it it subtracted now.
cumulativeActiveTime -= cumulativeActiveWaitingTime;
result += (latestTimeStamp - earliestTimeStamp) + ";" + cumulativeBlockedTime + ";" + cumulativeActiveWaitingTime + ";" + cumulativeActiveTime;
result += "\n";
}
return result.replace("\n", String.format("%n"));
}
}
/**
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package teetime.framework.performancelogging.formatstrategy;
import java.util.Collection;
import teetime.framework.AbstractStage;
import teetime.framework.StateStatistics;
import teetime.framework.performancelogging.ActivationStateLogger.IFormatingStrategy;
import teetime.framework.performancelogging.StateChange;
import teetime.framework.performancelogging.StateChange.StageActivationState;
/**
* Formating strategy to apply for percentage of active time.
*
* @author Adrian
*
*/
public class PercentageOfActiveTime implements IFormatingStrategy {
private final Collection<AbstractStage> stages;
public PercentageOfActiveTime(final Collection<AbstractStage> stages) {
this.stages = stages;
}
/**
* Will return the simple name of the given stage and added enough spaces to match the longest name.
*
* @param stage
* Stage which name should be formated.
* @return Simple name of the given stage plus spaces to match the longest name.
*/
String formateName(final AbstractStage stage) {
return stage.getClass().getSimpleName() + ";";
}
@Override
public String formatData() {
String result = "\n Formating of the data to get percentage of active time:\n\n";
result += "name;% active time\n";
for (AbstractStage stage : stages) {
result += formateName(stage);
boolean lastActive = false;
long lastActiveTimestamp = Long.MAX_VALUE;
long cumulativeActiveTime = 0;
long firstTimestamp = Long.MAX_VALUE;
long lastTimestamp = Long.MIN_VALUE;
for (StateChange state : StateStatistics.getStates(stage)) {
if (state.getTimeStamp() < firstTimestamp) {
firstTimestamp = state.getTimeStamp();
}
if (state.getTimeStamp() > lastTimestamp) {
lastTimestamp = state.getTimeStamp();
}
if (!lastActive && state.getStageActivationState() == StageActivationState.ACTIVE) {
lastActive = true;
lastActiveTimestamp = state.getTimeStamp();
}
if (lastActive && state.getStageActivationState() != StageActivationState.ACTIVE && lastActiveTimestamp != Long.MAX_VALUE) {
lastActive = false;
cumulativeActiveTime += (state.getTimeStamp() - lastActiveTimestamp);
}
}
result += ((double) cumulativeActiveTime / (double) (lastTimestamp - firstTimestamp)) * 100 + "\n";
}
return result.replace("\n", String.format("%n"));
}
}
/**
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package teetime.framework.performancelogging.formatstrategy;
import java.util.Collection;
import teetime.framework.AbstractStage;
import teetime.framework.StateStatistics;
import teetime.framework.performancelogging.ActivationStateLogger.IFormatingStrategy;
import teetime.framework.performancelogging.StateChange;
import teetime.framework.performancelogging.StateChange.StageActivationState;
/**
* Formating Strategy to apply the data to the Bottleneck Detection Approach of Roser, Nakano and Tanaka.
*
* @author Adrian
*
*/
public class RNTFormating implements IFormatingStrategy {
private final Collection<AbstractStage> stages;
public RNTFormating(final Collection<AbstractStage> stages) {
this.stages = stages;
}
/**
* Will return the simple name of the given stage and added enough spaces to match the longest name.
*
* @param stage
* Stage which name should be formated.
* @return Simple name of the given stage plus spaces to match the longest name.
*/
String formateName(final AbstractStage stage) {
return stage.getClass().getSimpleName() + ";";
}
@Override
public String formatData() {
String result = "\n Formating of the data to fit Approach of Roser, Nakano and Tanak:\n\n";
result += "name;Average ActiveTime (ns)\n";
// go through all the stages
for (AbstractStage stage : stages) {
// first add a formated version of their names to the line.
result += formateName(stage);
// will count the number of activeTimes
double counter = 0;
// stores the sum of active time
long cummulativeActiveTime = 0;
// stores the last relevant active time stamp
long lastActiveTimeStamp = 0;
// boolean to remember last state that was processed
boolean lastActive = false;
// go through all states of this stage and sum up the active times while counting the number of active times
for (StateChange state : StateStatistics.getStates(stage)) {
if (state.getStageActivationState() == StageActivationState.ACTIVE && !lastActive) {
lastActiveTimeStamp = state.getTimeStamp();
lastActive = true;
} else {
if (lastActive && lastActiveTimeStamp != 0) {
cummulativeActiveTime += (state.getTimeStamp() - lastActiveTimeStamp);
counter++;
}
lastActive = false;
}
}
// Add formated data to the line
result +=
// I differentiate between stages that were active the whole time and the ones that were interrupted in between.
// this will help to keep track of the necessary information.
((counter != 0) ? ((long) ((cummulativeActiveTime) / counter)) : cummulativeActiveTime);
result += "\n";
}
return result.replace("\n", String.format("%n"));
}
};
/**
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package teetime.framework.pipe;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import org.jctools.queues.QueueFactory;
import org.jctools.queues.spec.ConcurrentQueueSpec;
import org.jctools.queues.spec.Ordering;
import org.jctools.queues.spec.Preference;
import teetime.framework.AbstractPipe;
import teetime.framework.InputPort;
import teetime.framework.OutputPort;
import teetime.framework.signal.ISignal;
import teetime.framework.signal.StartingSignal;
import teetime.framework.signal.ValidatingSignal;
import teetime.util.framework.concurrent.queue.PCBlockingQueue;
import teetime.util.framework.concurrent.queue.putstrategy.PutStrategy;
import teetime.util.framework.concurrent.queue.putstrategy.YieldPutStrategy;
import teetime.util.framework.concurrent.queue.takestrategy.SCParkTakeStrategy;
import teetime.util.framework.concurrent.queue.takestrategy.TakeStrategy;
/**
*
* @author Christian Wulf
*
* @param <T>
* the type of the elements which this pipe should transfer.
*/
public abstract class AbstractSynchedPipe<T> extends AbstractPipe<T> {
private final BlockingQueue<ISignal> signalQueue;
private volatile boolean closed;
protected AbstractSynchedPipe(final OutputPort<? extends T> sourcePort, final InputPort<T> targetPort) {
super(sourcePort, targetPort);
final Queue<ISignal> localSignalQueue = QueueFactory.newQueue(new ConcurrentQueueSpec(1, 1, 0, Ordering.FIFO, Preference.THROUGHPUT));
final PutStrategy<ISignal> putStrategy = new YieldPutStrategy<ISignal>();
final TakeStrategy<ISignal> takeStrategy = new SCParkTakeStrategy<ISignal>();
signalQueue = new PCBlockingQueue<ISignal>(localSignalQueue, putStrategy, takeStrategy);
}
@Override
public void sendSignal(final ISignal signal) {
this.signalQueue.offer(signal);
}
/**
* Retrieves and removes the head of the signal queue
*
* @return Head of signal queue, <code>null</code> if signal queue is empty.
*/
public ISignal getSignal() {
return this.signalQueue.poll();
}
/**
* @deprecated since 3.0. Is removed without replacement.
*/
@Deprecated
@Override
public void reportNewElement() { // NOPMD
// default implementation
}
@Override
public final void waitForStartSignal() throws InterruptedException {
final ISignal signal = signalQueue.take();
if (signal instanceof ValidatingSignal) {
this.waitForStartSignal(); // recursive call
return;
}
if (!(signal instanceof StartingSignal)) {
throw new IllegalStateException(
"2001 - Expected StartingSignal, but was " + signal.getClass().getSimpleName() + " in " + getTargetPort().getOwningStage().getId());
}
cachedTargetStage.onSignal(signal, getTargetPort());
}
@Override
public final boolean isClosed() {
return closed;
}
@Override
public final void close() {
closed = true;
}
}
/**
* Copyright (C) 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime.sourceforge.net)
* Copyright © 2015 Christian Wulf, Nelson Tavares de Sousa (http://teetime-framework.github.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
......@@ -15,45 +15,52 @@
*/
package teetime.framework.pipe;
import java.util.LinkedList;
import teetime.framework.AbstractIntraThreadPipe;
import teetime.framework.AbstractPipe;
import teetime.framework.InputPort;
import teetime.framework.OutputPort;
import teetime.framework.signal.ISignal;
class OrderedGrowablePipe extends AbstractIntraThreadPipe {
/**
* Represents an unsynchronized pipe which can be used to connect stages within the same thread.
*
* @author Christian Wulf (chw)
*
* @param <T>
* the type of the elements which this pipe should transfer.
*/
public abstract class AbstractUnsynchedPipe<T> extends AbstractPipe<T> {
private final LinkedList<Object> elements;
private boolean closed;
<T> OrderedGrowablePipe(final OutputPort<? extends T> sourcePort, final InputPort<T> targetPort, final int capacity) {
protected AbstractUnsynchedPipe(final OutputPort<? extends T> sourcePort, final InputPort<T> targetPort) {
super(sourcePort, targetPort);
this.elements = new LinkedList<Object>();
}
@Deprecated
public static <T> void connect(final OutputPort<? extends T> sourcePort, final InputPort<T> targetPort) {
final IPipe pipe = new OrderedGrowablePipe(null, null, 100000);
pipe.connectPorts(sourcePort, targetPort);
@Override
public final void sendSignal(final ISignal signal) {
// getTargetPort is always non-null since the framework adds dummy ports if necessary
this.cachedTargetStage.onSignal(signal, this.getTargetPort());
}
@Override
public boolean add(final Object element) {
return this.elements.offer(element);
public final void reportNewElement() {
this.cachedTargetStage.executeByFramework();
}
@Override
public Object removeLast() {
return this.elements.poll();
public boolean isClosed() {
return closed;
}
@Override
public boolean isEmpty() {
return this.elements.isEmpty();
public void close() {
closed = true;
}
@SuppressWarnings("PMD.EmptyMethodInAbstractClassShouldBeAbstract")
@Override
public int size() {
return this.elements.size();
public void waitForStartSignal() throws InterruptedException {
// default implementation
}
}