March 25th, 2023 Generated Support

Past activation energy can be clear sailing, The future has yet to be written, The future has yet to be written, You can do it!, Nsdtp! Never Say Die Throughput!, Possible has yet to be defined, Encouragement Throughput has yet to be maximized, Possible is Power, Possible is Power, Nsdtp! Never Say Die Throughput!, Don’t forget an extra bottle of water can change a lot, Possible has yet to be defined, The future has yet to be written, You can do it!, Past activation energy can be clear sailing.

Initial conditions can mean a lot, Nsdtp! Never Say Die Throughput!, Encouragement Throughput has yet to be maximized, Encouragement Throughput has yet to be maximized, Possible has yet to be defined, Don’t forget an extra bottle of water can change a lot, There is hope in a New Day, Customer Experience and Quality can be Improved, Customer Experience and Quality can be Improved, Don’t forget an extra bottle of water can change a lot, You will Prevail!, There is hope in a New Day, Don’t forget an extra bottle of water can change a lot, Possible has yet to be defined, Possible is Power.

Don’t forget an extra bottle of water can change a lot, You can do it!, Others do not get to claim ground on what you can and cannot do, Customer Experience and Quality can be Improved, The future has yet to be written, There is hope in a New Day, Never Say Die!, Initial conditions can mean a lot, Customer Experience and Quality can be Improved, Possible has yet to be defined, You can do it!, Never Say Die!, Small changes do add up, You will Prevail!, Customer Experience and Quality can be Improved.

Nsdtp! Never Say Die Throughput!, Nsdtp! Never Say Die Throughput!, You will Prevail!, Others do not get to claim ground on what you can and cannot do, Initial conditions can mean a lot, Past activation energy can be clear sailing, You will Prevail!, Possible has yet to be defined, Small changes do add up, Possible has yet to be defined, Customer Experience and Quality can be Improved, Customer Experience and Quality can be Improved, Small changes do add up, Small changes do add up, Customer Experience and Quality can be Improved.

Possible has yet to be defined, Initial conditions can mean a lot, Others do not get to claim ground on what you can and cannot do, Possible is Power, There is hope in a New Day, Others do not get to claim ground on what you can and cannot do, The future has yet to be written, You will Prevail!, There is hope in a New Day, Customer Experience and Quality can be Improved, Possible is Power, Possible has yet to be defined, Never Say Die!, Never Say Die!, You can do it!.

You will Prevail!, The future has yet to be written, Small changes do add up, Initial conditions can mean a lot, Past activation energy can be clear sailing, Others do not get to claim ground on what you can and cannot do, There is hope in a New Day, Small changes do add up, Don’t forget an extra bottle of water can change a lot, Never Say Die!, Encouragement Throughput has yet to be maximized, Nsdtp! Never Say Die Throughput!, The future has yet to be written, The future has yet to be written, You can do it!.

The future has yet to be written, Don’t forget an extra bottle of water can change a lot, Past activation energy can be clear sailing, Never Say Die!, Others do not get to claim ground on what you can and cannot do, You can do it!, Possible has yet to be defined, Possible has yet to be defined, Customer Experience and Quality can be Improved, The future has yet to be written, Don’t forget an extra bottle of water can change a lot, Past activation energy can be clear sailing, Initial conditions can mean a lot, Never Say Die!, Past activation energy can be clear sailing.

Past activation energy can be clear sailing, Possible has yet to be defined, The future has yet to be written, There is hope in a New Day, You will Prevail!, Small changes do add up, You can do it!, There is hope in a New Day, Encouragement Throughput has yet to be maximized, Past activation energy can be clear sailing, Possible has yet to be defined, Possible is Power, Initial conditions can mean a lot, Possible is Power, Possible has yet to be defined.

Initial conditions can mean a lot, You can do it!, There is hope in a New Day, Don’t forget an extra bottle of water can change a lot, Don’t forget an extra bottle of water can change a lot, Initial conditions can mean a lot, Don’t forget an extra bottle of water can change a lot, Encouragement Throughput has yet to be maximized, Don’t forget an extra bottle of water can change a lot, Possible has yet to be defined, Customer Experience and Quality can be Improved, Possible has yet to be defined, Nsdtp! Never Say Die Throughput!, You can do it!, Encouragement Throughput has yet to be maximized.

Encouragement Throughput has yet to be maximized, Customer Experience and Quality can be Improved, Never Say Die!, The future has yet to be written, Nsdtp! Never Say Die Throughput!, Nsdtp! Never Say Die Throughput!, Don’t forget an extra bottle of water can change a lot, Past activation energy can be clear sailing, There is hope in a New Day, The future has yet to be written, Small changes do add up, Possible has yet to be defined, There is hope in a New Day, Never Say Die!, Past activation energy can be clear sailing.

Ethics, Clean Water Support, Improved Magnify Studio, Habitat for Humanity, Improved Chemical Showers for Labs, Critical Thinking, Criminal Defense Law, Improved Science Support, Water Well Drilling, Habitat for Humanity, Teacher Appreciation, Throughput, Improved Hospitals, Improved English Support, Improved Telescopes, Electrical Safety, More Peace, Time Management, Habitat for Humanity, Water Bottles, Improved English Support, More Peacemaking, Improved Fire Codes, Ethics, Reduced Villain Level Contrast Training

Improved Learning, Electrical Safety, Reduced Oppression, Improved English Support, More Peacemaking, Seat Belts, Improved Architectural Blueprints, More Peacekeeping, More Peace building, Teacher Appreciation, Improved Optics, Human Rights, Time Management, Water Bottles, More Peacekeeping, Throughput, Improved Medical Tech, Improved Optics, Improved Battery Power, Improved Math Support, Improved Science Support, Improved Fire Codes, Improved Learning, Respect, Validation

Electrical Safety, Improved Math Support, Improved Medical Tech, Linguistics Training, Carbon Monoxide Detectors, More Peacekeeping, Electrical Safety, Improved Network Throughput and Reach, Improved Medical Research, Cancer Research, Geneva Convention, Human Rights, Ethics, Encouragement, Seat Belts, Geneva Convention, Human Rights, Disaster Risk Reduction, Teacher Training, More Peace building, Motorcycle Helmets, Motorcycle Helmets, More Peace building, Electrical Safety, Clean Water Support

Motorcycle Helmets, Improved International Relations, Reduced Miscommunication, Improved Science Support, Time Management, Critical Thinking, Problem Solving, Improved Architectural Blueprints, More Peace building, Electrical Safety, Water Well Drilling, Human Rights, More Peacekeeping, Respect, Improved Math Support, Carbon Monoxide Detectors, Validation, Human Rights, Habitat for Humanity, Electrical Safety, Improved Math Support, Seat Belts, More Peace building, Reduced Oppression, Improved International Relations

Improved Magnify Studio, Improved Telescopes, Reduced Oppression, Improved Learning, Teacher Appreciation, Glass of Water, Improved Magnify Studio, Teacher Training, More Peacekeeping, Habitat for Humanity, Improved Learning, Cancer Research, Less Burning Buildings, Problem Solving, Rescue Blankets, Improved Learning, Throughput, Diversity Training, Teacher Training, Improved Network Throughput and Reach, Focus, Improved Math Support, Improved Hospitals, More Peacemaking, Habitat for Humanity

Improved Network Throughput and Reach, Human Rights, Improved Network Throughput and Reach, Improved Science Support, Reduced Villain Level Contrast Training, Rescue Blankets, Teacher Training, Glass of Water, Improved Chemical Showers for Labs, Reduced Villain Level Contrast Training, Geneva Convention, Improved Math Support, Diversity Training, Water Well Drilling, Glass of Water, Reduced Cognitive Biases Training, Throughput, Diversity Training, Improved Hospitals, Glass of Water, More Peacemaking, Carbon Monoxide Detectors, Cancer Research, Teacher Training, Improved Microscopes

Cancer Research, Improved Hospitals, Electrical Safety, Improved Microscopes, Human Rights, Improved Battery Power, Improved Fire Codes, Water Bottles, Carbon Monoxide Detectors, Water Well Drilling, Improved Science Support, Throughput, Water Bottles, Focus, Human Rights, Clean Water Support, Improved Battery Power, Diversity Training, Improved Research Ethics, Improved Medical Tech, Rescue Blankets, Focus, More Peacemaking, Rescue Blankets, Improved Telescopes

Clean Water Support, Encouragement, Linguistics Training, Reduced Child Labor, Child Car Safety, Defensive Driving, Critical Thinking, Reduced Miscommunication, Improved Telescopes, Reduced Oppression, Reduced Miscommunication, Improved Medical Tech, Less Burning Buildings, Improved Telescopes, More Peace building, Diversity Training, Cancer Research, Criminal Defense Law, Geneva Convention, Ethics, More Peacemaking, Improved Battery Power, Improved Architectural Blueprints, Problem Solving, Water Desalination Plants

Linguistics Training, Reduced Cognitive Biases Training, Linguistics Training, Motorcycle Helmets, Reduced Miscommunication, Teacher Appreciation, Improved Medical Tech, Human Rights, Reduced Oppression, Validation, Respect, Improved Battery Power, Water Well Drilling, Respect, Improved Microscopes, Problem Solving, Human Rights, Encouragement, More Peacemaking, Problem Solving, Reduced Oppression, Throughput, Improved International Relations, Human Rights, Improved Battery Power

Defensive Driving, Defensive Driving, Ethics, Clean Water Support, Throughput, Improved Research Ethics, Habitat for Humanity, Improved Medical Research, Respect, More Peace building, Improved English Support, Carbon Monoxide Detectors, More Peace, More Peacemaking, Time Management, Child Car Safety, Reduced Oppression, Improved Medical Tech, Time Management, Less Burning Buildings, Clean Water Support, Electrical Safety, Improved Medical Tech, Child Car Safety, Validation

Clean your room, Eat your vegetables, Never Say Die!Clean your room, Always be safe in the lab, Never Say Die!Do the dishes, Always be safe in the lab, Never Say Die!Do the dishes, Eat your vegetables, you hug the lovable dictatorClean your room, Do the dishes, you hug the lovable dictatorEat your vegetables, Go pick up some important documents from work, Never Say Die!Always be safe in the lab, Clean your room, you hug the lovable dictatorDo the dishes, Eat your vegetables, Never Say Die!Go pick up some important documents from work, Go pick up some important documents from work, Hug a kittenDo the dishes, Eat your vegetables, The prettiest flowers have the most leaves

Reaction Time, Acceleration, Potential Energy, Microeconomics, Blizzard, Quantum Entanglement, Disrespect, Gravity, Real Change, Energy, Charming, Public Relations, Active Volcano, Nitrogen, “Allegory of the Cave” – Plato, Sociology, Expert, Irrational, Disrespect, Precedent, Apples, Bugs, Defense Law, Open Loop Systems, Thunderstorm

Peaches, Imagination, Variance, Normal, Enthalpy, Motion, Story, “Allegory of the Cave” – Plato, Fault Tolerance, Communicated Effectively, Positive Momentum, Thunderstorm, Shape, Pineapples, Reducing Child Labor, Expert, Joules, Defense Law, Riddles, Open Loop Systems, Entropy, Slippery Slope, Hydroelectric Power, Projections, Knowns upsold to Unknowns

Slippery Slope, Villian Level Contrast Victims, Illogical, Radiation, Green Energy, Thunderstorm, Comprehension, Peaches, Unknowns upsold to Knowns, Geothermal Power, Nitrogen, Inequality, Normal, High Pressure, Probabilities, Communicated Effectively, Green Energy, Tone, Schrodinger’s Cat, Relevance, Interpolation, Trajectories, Initial Conditions, Magnetism, Drilling Water Wells

Stress, Weakest Link, Energy, Defense Law, Open Loop Systems, Validation, Red Herring, Cheesecake, Valence, Experience, Context Clues, Apples, Coffee, Communism, Fault Tolerance, Probabilities, Reasonable, Superposition, Potential Energy, Psychology, Inequality, Conductivity, Drag, Appreciation, Cocunut

Liquidity, Neutron, Wind Power, Fast Choice, Contamination, Flags, Health Care, Buy In, Pain, Unreasonable, Unreasonable, Peaches, Maintenance, Small Contributions Respected, Anger Management, Bagels, Fault Tolerance, Morally Wrong, Expert, Typhoon, Charming, Symbolism, Illogical, Communism, Volume

Story, Practical, Imperfect System upsold to Perfect in Very Non Ideal Ways, Mosquitos, Dental Care, Scientific Notation, Schrodinger’s Cat, Pineapples, Measurement, Anger Management, Cantelope, Water, Competition, Weak Hypothesis, Impossible, Shortest Path, Equality, Shortest Path, Delayed Right Choice, Bugs, Knowns upsold to Unknowns, Red Herring, “I think therefore I am” – Rene Descarte, Thunderstorm, Health Care

Dental Care, Speed of Sound, Fuses, Low Pressure, Cantelope, Morally Right, Combustion, Ethics, Charming, The Problem of Evil, Wind Power, Blizzard, Cover, Useful Work, 4th Dimension, Momentum, Bagels, Encouragement, Don’t push against a brick wall, Cover, Reaction Time, Orbits, Feedback, Fast Choice, Communicated Effectively

Mosquitos, Precision and Accuracy, Forms – Aristotle, Context Clues, Variety, Reducing Child Labor, Acceleration, Acronyms, Power Efficiency, Rate of Change, Teams, Disease, Neutron, Carbon Monoxide Detector, Discouragement, Induction, Disaster Risk Reduction, Ability to Change Path, Direction, Symbolism, Thunderstorm, Maintenance, Coffee, Disrespect, Mood, Velocity

Reaction Time, Latency, Communicated Effectively, Thermodynamics, Red Herring, Morally Wrong, Villian Level Contrast Victims, Don’t push against a brick wall, Active Volcano, Knowns upsold to Unknowns, Activation Energy, Surface Area, Equivocation, Feedback, Precedent, Imperfect System upsold to Perfect in Very Non Ideal Ways, Reversive Process, Coffee, Illogical, Pattern Matching, Directed Power, Context Clues, Delayed Right Choice, Plot, Disease

Feedback Respected, Kinetic Energy, Low Pressure, Multiple Dimensions, Limits, Normal, Theoretical Problem Solving, Scientific Method, Atmosphere, Tangled Cords, Disrespect, Accessibility, Insulation, Puns, Watts, Wind Power, Activation Energy, Metaphors, Fast Choice, Research Ethics, Competition, Plumbs, Logic, Value, Adequate Support

Current Average: 1375 ms

Updated my Math Addition problem app to call generate support after answering 25 questions correctly

25 Addition practices I wouldn’t have otherwise, support generated here I wouldn’t have otherwise

Calls generate support on every 25 answered correctly (where answeredCorreclty%25==0)

Updated this class a bit, Free Starter Java Class, MIT License

package application;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Logger;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import performance.PerformanceUtil;
import support.SupportMessageUtil;

public class Main extends Application {
	private Logger logger = Logger.getLogger(Main.class.getName());
	private Random random = new Random(System.nanoTime());
	private ArrayList<Integer> recordedTimes = new ArrayList<>();
	private int value1=2;
	private int value2=2;
	int questionsAnsweredCorrectly=0;
	
	public Canvas createCanvas() {
		Canvas canvas = new Canvas(25,25);
		canvasToColor(canvas,Color.RED);
		canvas.setWidth(25);
		canvas.setHeight(25);
		
		return canvas;
	}
	
	public void canvasToColor(Canvas canvas, Color color) {
		GraphicsContext graphicsContext = canvas.getGraphicsContext2D();
		graphicsContext.setFill(Paint.valueOf(color.toString()));
		graphicsContext.fillRect(0, 0, 25, 25);
	}
	
	Label encouragementLabel = new Label("Never Say Die!");
	Label problemSolvedInLabel = new Label("Problem Solved in:  ms");
	Label averageLabel = new Label("Average:  ms");
	
	class Question {
		int a;
		int b;
		int reanswerdRight=0;
	}
	
	ArrayList<Question> questionsAnsweredWrong = new ArrayList<>();
	
	BorderPane root = new BorderPane();
	Scene scene;
	VBox vbox = new VBox();
	Canvas canvas = createCanvas();
	Label answerCheckLabel;
	HBox hbox = new HBox();
	Label problemLabel;
	Label equalsLabel = new Label(" = ");
	TextField answerField = new TextField();
	
	private void setupComponents(Stage primaryStage) {
		setupRootElement(primaryStage);
		
		root.getChildren().add(vbox);
		vbox.getChildren().add(canvas);
		vbox.setMinHeight(400);

		setupAnswerCheckLabel();
		
		vbox.getChildren().add(hbox);			
		setupFormattingOnHorizontalBox();
		
		setupAndAddProblemLabels();
		
		hbox.getChildren().add(answerField);
		hbox.autosize();

		vbox.getChildren().addAll(encouragementLabel,problemSolvedInLabel,averageLabel);			
		vbox.autosize();
	}
	
	private void setupRootElement(Stage primaryStage) {
		scene = new Scene(root,400,500);
		scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
		primaryStage.setScene(scene);			
		primaryStage.show();
	}
	
	private void setupAnswerCheckLabel() {
		answerCheckLabel = new Label("Test");
		answerCheckLabel.setMinWidth(400);
		answerCheckLabel.setMinHeight(200);
		answerCheckLabel.setAlignment(Pos.CENTER);
		vbox.getChildren().add(answerCheckLabel);
	}
	
	private void setupFormattingOnHorizontalBox() {
		hbox.setPadding(new Insets(10,10,10,10));
		hbox.setMinWidth(400);
		hbox.setMinHeight(200);
		hbox.setAlignment(Pos.CENTER);
	}
	
	private void setupAndAddProblemLabels() {
		problemLabel = new Label(value1+" + "+value2);
		problemLabel.setFont(Font.font(20));
		PerformanceUtil.getInstance().start();
		hbox.getChildren().add(problemLabel);
		hbox.getChildren().add(equalsLabel);
	}
	
	private void processCorrectAnswer() {
		logAndDisplayAnswerIsCorrect();
	}
	
	private void logAndDisplayAnswerIsCorrect() {
		canvasToColor(canvas,Color.GREEN);
		answerCheckLabel.setText("Answer is correct");
		System.out.println("Answer is correct");
		PerformanceUtil.getInstance().stop();
		System.out.println("Problem solved in: "+PerformanceUtil.getInstance().getRecordedTime()+" ns");
		System.out.println("Problem solved in: "+PerformanceUtil.getInstance().getRecordedTimeMilliseconds()+" ms");
		recordedTimes.add(PerformanceUtil.getInstance().getRecordedTimeMilliseconds());
		problemSolvedInLabel.setText("Problem Solved in: "+PerformanceUtil.getInstance().getRecordedTimeMilliseconds()+" ms");
		
		questionsAnsweredCorrectly++;
		
		displayEncouragementAlertOrAskAnotherQuestion();
	}
	
	private void displayEncouragementAlertOrAskAnotherQuestion() {
		if (questionsAnsweredCorrectly%25==0) {
			String support = SupportMessageUtil.generateSupport();
			logger.info(support);
			Alert alert = new Alert(AlertType.INFORMATION);
			alert.setTitle("Good Work! Never Say Die!");
			alert.setHeaderText(questionsAnsweredCorrectly+" Questions Answered Correctly!");
			alert.setContentText("Good Work! Never Say Die!");
			alert.show();
			alert.setOnCloseRequest((event) -> {
				finishProcessCorrectAnswer();
			});
     	} else {
     		finishProcessCorrectAnswer();
     	}
	}
	
	private void finishProcessCorrectAnswer() {
		computeAverage();
		reduceOrRemoveFromQuestionsAnsweredWrongList();		
		loadNewQuestion();
	}
	
	private void reduceOrRemoveFromQuestionsAnsweredWrongList() {
		List<Question> questions = questionsAnsweredWrong.stream().filter(q -> q.a==value1 && q.b==value2).toList();
		
		if (questions.size()>0) {
			Question question = questions.get(0);
			question.reanswerdRight++;
			if (question.reanswerdRight==3) { // Answered right 3 times, remove from questionsAnsweredWrong
				logger.info("Wrong Question Answered Right 3 times");
				questionsAnsweredWrong.remove(question);
			}
		}		
	}
	
	private void loadNewQuestion() {
		answerField.setText("");
		
		// 1 out of 4 times ask missed question
		if (questionsAnsweredWrong.size()>0 && random.nextInt(0,3)==0) {
			logger.info("Reasking Wrong Question");
			// get random element from questonsAnsweredWrong
			int randomElement = random.nextInt(0,questionsAnsweredWrong.size());
			Question question = questionsAnsweredWrong.get(randomElement);
			value1 = question.a;
			value2 = question.b;
		} else {
			value1 = random.nextInt(0,10);
			value2 = random.nextInt(0,10);
		}
		PerformanceUtil.getInstance().start();
		problemLabel.setText(value1+" + "+value2);		
	}
	
	private void processIncorrectAnswer() {
		List<Question> questions = questionsAnsweredWrong.stream().filter(q -> q.a==value1 && q.b==value2).toList();
		
		if (questions.size()>0) {
			questions.get(0).reanswerdRight--;
		} else {
			Question question = new Question();
			question.a = value1;
			question.b = value2;
			questionsAnsweredWrong.add(question);
		}
		
		
		canvasToColor(canvas,Color.RED);
		answerCheckLabel.setText("Answer is incorrect");
		System.out.println("Answer is incorrect");
		System.out.println("Problem solving running time: "+PerformanceUtil.getInstance().getRunningTime()+" ns");
	}
	
	private void handleAnswerEvent() {
		System.out.println("Enter Key Released: "+answerField.getText());
		try {					
			int value = Integer.parseInt(answerField.getText());
			int sum = value1+value2;
			if (value == sum) {
				processCorrectAnswer();
			} else {
				processIncorrectAnswer();
			} 
		} catch (NumberFormatException e) {
			System.out.println("Could not parse number");
		}		
	}
	
	@Override
	public void start(Stage primaryStage) {
		try {
			setupComponents(primaryStage);
			
			answerField.setFont(Font.font(20));
			answerField.setOnKeyReleased((event) -> {
				KeyEvent keyEvent = (KeyEvent) event;
				if (event.getCode()==KeyCode.ENTER) {
					handleAnswerEvent();
				}
			});
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public void computeAverage() {
		int sum=0;
		for (int i=0; i<recordedTimes.size(); i++) {
			sum+=recordedTimes.get(i);
		}
		int average = sum/recordedTimes.size();
		System.out.println("Current Average: "+average+" ms");
		averageLabel.setText("Average: "+average+" ms");
	}
	
	public static void main(String[] args) {
		launch(args);
	}
}

Splitting this up into multiple files with a Model View Controller setup can increase the ability to maintain it. One file is useful for getting people moving with Java and JavaFX more swiftly. Getting it to run still requires Java and JavaFX packages, also my support generation library would be available if I was not being limited. Thus the generate support method currently will not.

Society likely cursed with less support until they stop limiting me.

Now Society in 2400 will have a head start App to facilitate Math Learning

Wise to invest in appreciation for people that can add 25 numbers correctly. Why you ask? Artificial Intelligence has the potential to replace many if not all jobs. Humans rewarded for doing small tasks right is something we want to invest in for future generations.

Mean society took away my Pattern Matching lesson for the world.

https://en.wikipedia.org/wiki/Pattern_matching

May regular expressions function better for those not involved.

https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

[c]or[rabc]uption?

https://www.w3schools.com/java/java_regex.asp

If the [sabc]hoe [efg]its, Pattern.compile()

[4-9] fired executives possible?

The pattern says greater than 3

flatMap vs map on Streams API?

https://stackoverflow.com/questions/69010763/pattern-matching-using-java-streams

https://www.baeldung.com/java-difference-map-and-flatmap

https://www.geeksforgeeks.org/difference-between-map-and-flatmap-in-java-stream/

Pattern matching with Streams API, take and break upon sentences of paragraphs (“period”). Then take that list of sentences and create a list of all words that start with S.

So if you have a paragraph like this. Then state sally sells seashells. Potentially at the sea shore.

Output list should look like

[So, state, sally, sells, seashells, sea, shore]

period is a special character in Pattern matcher class, thus needs to be escaped like “\\.” to split on sentences

        String testString = "So if you have a paragraph like this.  Then state sally sells seashells.  Potentially at the sea shore.";

        System.out.println("Test String: "+testString);

        List<String> sentences = List.of(testString.split("\\."));
        List<String> sWords = List.of(testString.split("\\."))
                .stream().flatMap((element) -> {
                    String words[] = element.split(" ");
                    List<String> sWordsInSentence = List.of(words)
                            .stream().filter((word) -> word.matches("[Ss].*")).toList();
                    return sWordsInSentence.stream();
                }).toList();

        sWords.stream().forEach((element) -> System.out.println(element));

Outputs the following

Test String: So if you have a paragraph like this.  Then state sally sells seashells.  Potentially at the sea shore.
So
state
sally
sells
seashells
sea
shore

A good reminder for Alliteration

Probably could be tailored to pick out instances of Alliteration from a novel.

When does a set of words officially qualify as alliteration? Two words or Three words?

Show Something Powerfully Proclaimed?

Macroscopic Magnificent Metaphorical Metaphironizing Juxtaphorsition?

Can easily be tailored to pull out all the words based upon letter

Needs to be a utility class for all the letters in alphabet, maybe there is one already built into Java.

Looks like char can be incremented using ++ thus char letter = ‘c’++; equals d or c? vs char letter = ++”c”;? Looks like ++ requires a variable

        char letter1 = 'c';
        System.out.println('c');
        System.out.println("letter1++"+letter1++);
        System.out.println("++letter1"+(++letter1));

Prints the following

c
letter1++c
++letter1e

Looks like Variable++ increments the letter to d after printing

Looks like ++Variable increments the letter to e then prints

Updated the code

        String testString = "So if you have a paragraph like this.  Then state sally sells seashells.  Potentially at the sea shore.";

        System.out.println("Test String: "+testString);

        char letter1 = 'c';
        System.out.println('c');
        System.out.println("letter1++"+letter1++);
        System.out.println("++letter1"+(++letter1));

        for (char letter='a'; letter<='z'; letter++) {
            char upperCase = Character.toUpperCase(letter);
            String pattern = "["+upperCase+letter+"].*";
            System.out.print(""+upperCase+letter+" - ");
            List<String> sWords = List.of(testString.split("\\."))
                    .stream().flatMap((element) -> {
                        String words[] = element.split(" ");
                        List<String> sWordsInSentence = List.of(words)
                                .stream().filter((word) -> word.matches(pattern)).toList();
                        return sWordsInSentence.stream();
                    }).toList();

            sWords.stream().forEach((element) -> System.out.print(element+" "));
            System.out.print("\n");
        }

Outputs

Test String: So if you have a paragraph like this.  Then state sally sells seashells.  Potentially at the sea shore.
c
letter1++c
++letter1e
Aa - a at 
Bb - 
Cc - 
Dd - 
Ee - 
Ff - 
Gg - 
Hh - have 
Ii - if 
Jj - 
Kk - 
Ll - like 
Mm - 
Nn - 
Oo - 
Pp - paragraph Potentially 
Qq - 
Rr - 
Ss - So state sally sells seashells sea shore 
Tt - this Then the 
Uu - 
Vv - 
Ww - 
Xx - 
Yy - you 
Zz - 

Can be further updated to count number of times each word is used

Useful tool for writers to know which words they are using most. Potentially useful for editors.

Updated further

        String testString = "So if you have a paragraph like this.  Then state sally sells seashells.  Potentially at the sea shore.";

        System.out.println("Test String: "+testString);

        char letter1 = 'c';
        System.out.println('c');
        System.out.println("letter1++"+letter1++);
        System.out.println("++letter1"+(++letter1));

        HashMap<String,List<String>> lettersWords = new HashMap<>();

        for (char letter='a'; letter<='z'; letter++) {
            char upperCase = Character.toUpperCase(letter);
            String pattern = "["+upperCase+letter+"].*";
            String upperAndLower = ""+upperCase+letter;
            List<String> sWords = List.of(testString.split("\\."))
                    .stream().flatMap((element) -> {
                        String words[] = element.split(" ");
                        List<String> sWordsInSentence = List.of(words)
                                .stream().filter((word) -> word.matches(pattern)).toList();
                        return sWordsInSentence.stream();
                    }).toList();
            if (sWords.size()>0) {
                lettersWords.put(upperAndLower, sWords);
            }
        }

        lettersWords.forEach((key,elements) -> {
            System.out.println(key+ " - "+elements.toString());
        });

Output is the following

Test String: So if you have a paragraph like this.  Then state sally sells seashells.  Potentially at the sea shore.
c
letter1++c
++letter1e
Aa - [a, at]
Hh - [have]
Ii - [if]
Ll - [like]
Pp - [paragraph, Potentially]
Ss - [So, state, sally, sells, seashells, sea, shore]
Tt - [this, Then, the]
Yy - [you]

Counting matching elements in java?

Looks like there is a Collections.frequency

https://www.w3docs.com/snippets/java/how-to-count-the-number-of-occurrences-of-an-element-in-a-list.html#:~:text=in%20a%20List-,To%20count%20the%20number%20of%20occurrences%20of%20an%20element%20in,element%20appears%20in%20the%20collection.

Updated now is printing out the following

Test String: So if you have a paragraph like this.  Then state sally sells seashells.  Potentially at the sea shore. This is a test sentence that promotes unit test testing where the word test is used in more than one test.
c
letter1++c
++letter1e
Aa - 
   a - 2
   at - 1
   a - 2
Ii - 
   if - 1
   is - 2
   is - 2
   in - 1
Mm - 
   more - 1
Oo - 
   one - 1
Ss - 
   So - 1
   state - 1
   sally - 1
   sells - 1
   seashells - 1
   sea - 1
   shore - 1
   sentence - 1
Uu - 
   unit - 1
   used - 1
Ww - 
   where - 1
   word - 1
Yy - 
   you - 1
Hh - 
   have - 1
Ll - 
   like - 1
Pp - 
   paragraph - 1
   Potentially - 1
   promotes - 1
Tt - 
   this - 1
   Then - 1
   the - 2
   This - 1
   test - 4
   that - 1
   test - 4
   testing - 1
   the - 2
   test - 4
   than - 1
   test - 4

The code that output was generated from is as following:

        String testString = "So if you have a paragraph like this.  Then state sally sells seashells.  Potentially at the sea shore. This is a test sentence that promotes unit test testing where the word test is used in more than one test.";

        System.out.println("Test String: "+testString);

        char letter1 = 'c';
        System.out.println('c');
        System.out.println("letter1++"+letter1++);
        System.out.println("++letter1"+(++letter1));

        HashMap<String,List<String>> lettersWords = new HashMap<>();

        for (char letter='a'; letter<='z'; letter++) {
            char upperCase = Character.toUpperCase(letter);
            String pattern = "["+upperCase+letter+"].*";
            String upperAndLower = ""+upperCase+letter;
            List<String> sWords = List.of(testString.split("\\."))
                    .stream().flatMap((element) -> {
                        String words[] = element.split(" ");
                        List<String> sWordsInSentence = List.of(words)
                                .stream().filter((word) -> word.matches(pattern)).toList();
                        return sWordsInSentence.stream();
                    }).toList();
            if (sWords.size()>0) {
                lettersWords.put(upperAndLower, sWords);
            }
        }

        lettersWords.forEach((key,elements) -> {
            System.out.println(key+ " - ");
            elements.forEach((element) -> {
                System.out.println("   "+element+" - "+ Collections.frequency(elements,element));
            });
        });

Worthwhile to move that count to another HashMap

        HashMap<String,Integer> wordCount = new HashMap<>();

        lettersWords.forEach((key,elements) -> {
            elements.forEach((element) -> {
                int frequency = Collections.frequency(elements,element);
                wordCount.put(element,frequency);
            });
        });

        wordCount.forEach((key,count) -> {
            System.out.println(key+" - "+count);
        });

HashMap does not maintain order, worth noting

paragraph - 1
used - 1
sea - 1
that - 1
than - 1
have - 1
This - 1
where - 1
Then - 1
state - 1
promotes - 1
if - 1
you - 1
sentence - 1
a - 2
test - 4
in - 1
sells - 1
seashells - 1
like - 1
more - 1
one - 1
testing - 1
shore - 1
this - 1
sally - 1
is - 2
the - 2
unit - 1
at - 1
Potentially - 1
So - 1
word - 1

Potentially a useful bar of measurement for future programming languages, how many lines of code does it require to break a novel of text into word counts.

Streams and counts are useful, ability to process each paragraph of a novel like stream into increments to word counts in a HashMap.

I wonder how find in file works with differently formatted files. Find in a zip file likely requires unzipping.

https://7-zip.org/

Simple programming task? Java has zip and unzip utilities built in. Search a file as normal if .txt and if file extension is zip, unzip then search files that are .txt?

A script that could search compressed files swiftly created in advance could likely save a lot of time.

Potentially useful for a performance test, add some gigabyte sized zip files and compute search to result time for new systems. Search potentially a concurrent problem when data transfer is not the weakest link. Processing on multiple files is possible. If the CPU processes faster than hard drive gets data into memory then there could be an issue with bottlenecked via the hard drive data transfer speed.

Precomputed and preprocessed lazy loaded values already generated into documents potentially more useful as data transfer becomes fast and cheap. All potential states of an application potentially replicable.

Society invests in processing, does not always capitalize on processing already completed. If a map of sin and cos values could be generated for 0.1 increments of degrees on 360 degrees, thus 3600 different values, would those 3600 different values in an array be cheaper than formula required to generate sine or cosine?

Potential for common math functions that are reused time and time again to be mapped into very fast cache like memory that requires less computation. Able to generalize computation is useful, potential for enabling the future based upon calculations made today is easily forgotten.

Profiling knowledge about what methods are called the most and what methods take the longest to complete factors into flagged potential for greater throughput.

Backgrounds in images move less (further away from the action) potential for able to cache more.

Sine of 3.14 from map: 0.0015926529165099209
Computed sine: 0.0015926529164868282

Cosine of 3.14 from map: -0.9999987317275395
Computed cosine: -0.9999987317275395

Tan of 3.14 from map: -0.0015926549364303157
Computed Tan of 3.14: -0.001592654936407223

Swift ways to verify can be powerful

       double twoPi=Math.PI*2;
        HashMap<String,Double> sineMap = new HashMap<>();
        HashMap<String,Double> cosineMap = new HashMap<>();
        HashMap<String,Double> tanMap = new HashMap<>();
        for (double r=0.0; r<twoPi; r+=0.01) {
            DecimalFormat decimalFormat = new DecimalFormat();
            String valueAsTwoDigitString = String.format("%.2f",r);
            sineMap.put(valueAsTwoDigitString, Math.sin(r));
            cosineMap.put(valueAsTwoDigitString, Math.cos(r));
            tanMap.put(valueAsTwoDigitString, Math.tan(r));
        }

        System.out.println("Sine of 3.14 from map: "+sineMap.get("3.14"));
        System.out.println("Computed sine: "+Math.sin(3.14)+'\n');

        System.out.println("Cosine of 3.14 from map: "+cosineMap.get("3.14"));
        System.out.println("Computed cosine: "+Math.cos(3.14)+'\n');

        System.out.println("Tan of 3.14 from map: "+tanMap.get("3.14"));
        System.out.println("Computed Tan of 3.14: "+Math.tan(3.14)+'\n');

one million executions of Math.sin(3.14) vs one million gets from the same hashmap?

first run, timed in milliseconds

Sine from HashMap for 1 million calls: 23
Sine computed for 1 million calls: 17

from following code

        double value;
        double computedValue;
        PerformanceUtil.getInstance().startInstant();
        for (int i=0; i<1_000_000; i++) {
            computedValue = sineMap.get("3.14");
            computedValue += i;
        }
        PerformanceUtil.getInstance().stopInstant();

        long time1Milliseconds = PerformanceUtil.getInstance().getInstantDifferenceMilliseconds();

        PerformanceUtil.getInstance().startInstant();
        for (int i=0; i<1_000_000; i++) {
            computedValue = Math.sin(3.14);
            computedValue += i;
        }
        PerformanceUtil.getInstance().stopInstant();

        long time2Milliseconds = PerformanceUtil.getInstance().getInstantDifferenceMilliseconds();

        System.out.println("Sine from HashMap for 1 million calls: "+time1Milliseconds);
        System.out.println("Sine computed for 1 million calls: "+time2Milliseconds);

One would expect the same call to HashMap one million times would execute faster than just computing sine

Changing the code to

        double value;
        double computedValue;
        PerformanceUtil.getInstance().startInstant();
        computedValue = sineMap.get("3.14");
        double inLoopValue;
        for (int i=0; i<1_000_000; i++) {
            inLoopValue = computedValue;
            inLoopValue += i;
        }
        PerformanceUtil.getInstance().stopInstant();

        long time1Milliseconds = PerformanceUtil.getInstance().getInstantDifferenceMilliseconds();

        PerformanceUtil.getInstance().startInstant();
        for (int i=0; i<1_000_000; i++) {
            computedValue = Math.sin(3.14);
            computedValue += i;
        }
        PerformanceUtil.getInstance().stopInstant();

        long time2Milliseconds = PerformanceUtil.getInstance().getInstantDifferenceMilliseconds();

        System.out.println("Sine from HashMap for 1 million calls: "+time1Milliseconds);
        System.out.println("Sine computed for 1 million calls: "+time2Milliseconds);

Changes output to

Sine from HashMap for 1 million calls: 10
Sine computed for 1 million calls: 18

Though output likely can change given current processing load on the system.

Second run

Sine from HashMap for 1 million calls: 11
Sine computed for 1 million calls: 19

Good to know stored variable access cheaper than two calls to a HashMap

Precision is useful enabled in certain directions, capitalizing on that can be high value added

A more complicated problem that might be something like sine of x2 cosine of x3 and tan of x4, if computed for similar radians and precision need not be ideal could likely be computed in advance and stored in a HashMap.

Overly complicated math problems that can be computed in advance to become a simple get this value can be powerful as long as greater precision is unlikely to be required in the near future.

Like a boolean sunInSky true or false. Could be useful in regions for determining if it is night or day in regions where cloud cover might be less.

How precise location of sunInSky needs to be tracked? For applications like solar panel controllers? Solar panels that automatically track the sun

A transistor with 8 different states versus on and off. Two of those transistors could hold how many states?

64 states

Add in one more and that grows to 512 states

If one could take the top 512 Words used in the English language and assign each of them one of those states

512 is Oct 1000

Thus 511 is Oct 777

Possibly could be compressed further with top 512 phrases in English

00 Please try again
01 There is a bug in the software
10 We need to test more
11 The solution is ready for prime time

A lot could be communicated with a short encoding

10? When we need to be at 11?

When will we be at 11?

How many 01s?

100 – Never Say Die!

101 – There is no time for that?

Moving up to 10_000_000 calls, in milliseconds

Sine from HashMap for 1 million calls: 18
Sine computed for 1 million calls: 240

thus at 50_000_000 calls

Sine from HashMap for 1 million calls: 18
Sine computed for 1 million calls: 677

Forgetting to update the output statements easy to do

        double value;
        double computedValue;
        PerformanceUtil.getInstance().startInstant();
        computedValue = sineMap.get("3.14");
        double inLoopValue;
        for (int i=0; i<1_000_000_000; i++) {
            inLoopValue = computedValue;
            inLoopValue += i;
        }
        PerformanceUtil.getInstance().stopInstant();

        long time1Milliseconds = PerformanceUtil.getInstance().getInstantDifferenceMilliseconds();

        PerformanceUtil.getInstance().startInstant();
        for (int i=0; i<1_000_000_000; i++) {
            computedValue = Math.sin(3.14);
            computedValue += i;
        }
        PerformanceUtil.getInstance().stopInstant();

        long time2Milliseconds = PerformanceUtil.getInstance().getInstantDifferenceMilliseconds();

        System.out.println("Sine from HashMap for 1 billion calls: "+time1Milliseconds);
        System.out.println("Sine computed for 1 billion calls: "+time2Milliseconds);

Output in milliseconds is

Sine from HashMap for 1 billion calls: 17
Sine computed for 1 billion calls: 11375

Thus for one billion calls to sine of Math.sine(3.14) the precomputed value plus an addition takes 17 milliseconds where as a call to Math.sine(3.14) on each call incurs an 11 second loss.

Sine of pi is 0 and Cosine of pi is -1 computed and known in advance is power.

PI is 180 degrees, 2 PI is 360 degrees, Windows Calculator plus Scientific mode uses degrees by default

Potential for a Cached Lazy Loaded Math Sine function that could increase performance in Java

limit the hashmap keys to a certain number of decimal places

if not computed before, compute then add to map

LazyLoadedMathUtil?

Java Class I have created but have not tested yet, I provide freely, MIT License

package math;

import java.util.HashMap;

public class LazyLoadedMathUtil {
	private static int decimalPlacesOfPrecision=3;
	private static HashMap<String, Double> sineMap = new HashMap<>();
	private static HashMap<String, Double> cosineMap = new HashMap<>();
	private static HashMap<String, Double> tanMap = new HashMap<>();
	private static String decimalFormatPattern = "%."+decimalPlacesOfPrecision+"f";
	
	public double sine(double radians) {
		String parameter = String.format(decimalFormatPattern,radians);
		Double value = sineMap.get(parameter);
		if (null!=value) {
			value = Math.sin(radians);
			sineMap.put(parameter, value);
		}

		return value;		
	}	

	public double cos(double radians) {
		String parameter = String.format(decimalFormatPattern,radians);
		Double value = cosineMap.get(parameter);
		if (null!=value) {
			value = Math.cos(radians);
			sineMap.put(parameter, value);
		}

		return value;		
	}
	
	public double tan(double radians) {
		String parameter = String.format(decimalFormatPattern,radians);
		Double value = tanMap.get(parameter);
		if (null!=value) {
			value = Math.tan(radians);
			sineMap.put(parameter, value);
		}

		return value;		
	}	
}

Potential to tune to cost of HashMap search time

Updated

package math;

import java.util.HashMap;

public class LazyLoadedMathUtil {
	private static int decimalPlacesOfPrecision=3;
	private static HashMap<String, Double> sineMap = new HashMap<>();
	private static HashMap<String, Double> cosineMap = new HashMap<>();
	private static HashMap<String, Double> tanMap = new HashMap<>();
	private static String decimalFormatPattern = "%."+decimalPlacesOfPrecision+"f";
	
	public static double sine(double radians) {
		String parameter = String.format(decimalFormatPattern,radians);
		Double value = sineMap.get(parameter);
		if (null==value) {
			value = Math.sin(radians);
			sineMap.put(parameter, value);
		}

		return value;		
	}	

	public static double cos(double radians) {
		String parameter = String.format(decimalFormatPattern,radians);
		Double value = cosineMap.get(parameter);
		if (null==value) {
			value = Math.cos(radians);
			sineMap.put(parameter, value);
		}

		return value;		
	}
	
	public static double tan(double radians) {
		String parameter = String.format(decimalFormatPattern,radians);
		Double value = tanMap.get(parameter);
		if (null==value) {
			value = Math.tan(radians);
			sineMap.put(parameter, value);
		}

		return value;		
	}	
}

HashMap calls are cheap in some cases, far from free

Following output

Sine from HashMap for 1 million calls: 11 ms
Sine computed for 1 million calls: 22 ms
Sine from LazyLoadedMathUtil for 1 million calls: 742 ms
Sine from LazyLoadedMathUtil for 1 million calls loaded outside of loop: 11 ms

Based on

        double value;
        double computedValue;
        PerformanceUtil.getInstance().startInstant();
        computedValue = sineMap.get("3.14");
        double inLoopValue;
        for (int i=0; i<1_000_000; i++) {
            inLoopValue = computedValue;
            inLoopValue += i;
        }
        PerformanceUtil.getInstance().stopInstant();

        long time1Milliseconds = PerformanceUtil.getInstance().getInstantDifferenceMilliseconds();

        PerformanceUtil.getInstance().startInstant();
        for (int i=0; i<1_000_000; i++) {
            computedValue = Math.sin(3.14);
            computedValue += i;
        }
        PerformanceUtil.getInstance().stopInstant();

        long time2Milliseconds = PerformanceUtil.getInstance().getInstantDifferenceMilliseconds();

        PerformanceUtil.getInstance().startInstant();
        for (int i=0; i<1_000_000; i++) {
            computedValue = LazyLoadedMathUtil.sine(3.14);
            computedValue += i;
        }
        PerformanceUtil.getInstance().stopInstant();

        long time3Milliseconds = PerformanceUtil.getInstance().getInstantDifferenceMilliseconds();

        PerformanceUtil.getInstance().startInstant();
        computedValue = LazyLoadedMathUtil.sine(3.14);
        for (int i=0; i<1_000_000; i++) {
            inLoopValue = computedValue;
            inLoopValue += i;
        }
        PerformanceUtil.getInstance().stopInstant();

        long time4Milliseconds = PerformanceUtil.getInstance().getInstantDifferenceMilliseconds();

        System.out.println("Sine from HashMap for 1 million calls: "+time1Milliseconds+" ms");
        System.out.println("Sine computed for 1 million calls: "+time2Milliseconds+" ms");
        System.out.println("Sine from LazyLoadedMathUtil for 1 million calls: "+time3Milliseconds+" ms");
        System.out.println("Sine from LazyLoadedMathUtil for 1 million calls loaded outside of loop: "+time4Milliseconds+" ms");

Processing excessive amounts on main thread can freeze up JavaFX User Interface, I moved the following to a different thread

        ThreadUtil.addTask( () -> {
            double computedThreadValue;
            PerformanceUtil.getInstance().startInstant();
            for (int i=0; i<1_000_000_000; i++) {
                computedThreadValue = LazyLoadedMathUtil.sine(3.14);
                if (i%10_000_000==0)
                {
                    System.out.println("Computed iterations: "+i);
                }
                computedThreadValue += i;
            }
            PerformanceUtil.getInstance().stopInstant();
            long time3Milliseconds = PerformanceUtil.getInstance().getInstantDifferenceMilliseconds();

            System.out.println("Sine from LazyLoadedMathUtil for 1 billion calls: "+time3Milliseconds+" ms");
        });

Prints out every 10 million iterations and takes substantially longer

Not every day that a simple choice between something in the loop versus outside of the loop can completely change performance

Many method calls can be one offs and not called many times

Might be useful for gauging future computer performance, how long 1 billion calls to the same HashMap value takes

Operations that require lots of HashMap calls likely good candidates for multithreading

Output finally arrived

....
Computed iterations: 900000000
Computed iterations: 910000000
Computed iterations: 920000000
Computed iterations: 930000000
Computed iterations: 940000000
Computed iterations: 950000000
Computed iterations: 960000000
Computed iterations: 970000000
Computed iterations: 980000000
Computed iterations: 990000000
Sine from LazyLoadedMathUtil for 1 billion calls: 474208 ms

474 seconds / 60 = 7.83 minutes

Updated using my ThreadUtil and ThreadOrderProcess classes to run in Paralle

        ThreadUtil.addTask( () -> {
                    Runnable method = () -> {
                        double computedThreadValue;

                        for (int i = 0; i < 250_000_000; i++) {
                            computedThreadValue = LazyLoadedMathUtil.sine(3.14);
                            if (i % 10_000_000 == 0) {
                                System.out.println("Computed iterations: " + i);
                            }
                            computedThreadValue += i;
                        }

                    };

                    ArrayList<Runnable> parallelTasks = new ArrayList<>(List.of(method, method, method, method));

                    PerformanceUtil.getInstance().startInstant();
                    ThreadOrderProcessUtil.runParallelProcess("Lazy Loaded Math Calls", parallelTasks, true);
                    PerformanceUtil.getInstance().stopInstant();
                    long time3Milliseconds = PerformanceUtil.getInstance().getInstantDifferenceMilliseconds();

                    System.out.println("Sine from LazyLoadedMathUtil for 4*250 million calls: " + time3Milliseconds + " ms");
                });

Potentially not thread safe, all might need their own version of the lazy loaded hashmap. While race condition less likely in this case possible in other cases.

Found an odd bug where a particular logging line caused the JVM to exit

First result with slight lag due to a debug line added

process complete successful
Sine from LazyLoadedMathUtil for 4*250 million calls: 150362 ms

2.5 minutes using 4 cores to make calls to the Lazy Loaded HashMap vs 8 minutes for 1 core for 1 billion calls.

without the breakpoint, this time

process complete successful
Sine from LazyLoadedMathUtil for 4*250 million calls: 151300 ms

very odd one line of logging code is causing JVM to break

package process;

import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

import multithreading.ThreadUtil;

public class ThreadOrderProcessUtil {
	private static Logger logger = Logger.getLogger(ThreadOrderProcessUtil.class.getName());
	
	private static void log(final boolean enableLog, final String message) {
		if (enableLog) {
			logger.info(message);
		}
	}
	
	public static ProcessComplete runSequentialProcess(String processName, ArrayList<Runnable> sequentialProcessList, 
			boolean enableLog) {
		log(enableLog,processName+" started");
		
		try {
			for (int i=0; i<sequentialProcessList.size(); i++) {			
				Runnable step = sequentialProcessList.get(i);
				log(enableLog,processName+" running step "+i);
				step.run();
				log(enableLog,processName+" completed step "+i);
			}
			
			log(enableLog,processName+" finished successfully");
			return new ProcessComplete(true, true);
		} catch (Exception e) {
			return new ProcessComplete(true, false);
		}
	}
	
	
	
	public static ArrayList<Runnable> lastProcessed;
	
	// Method that runs a set of Parallel tasks and then blocks/sleeps/polls until all
	// queued threads are complete
	// *********************************************
	// TODO: Fix nasty buy where process shows as completed does not line up with versioning on classes
	public static ProcessComplete runParallelProcess(String processName, ArrayList<Runnable> parallelProcessList,
			boolean enableLog)
	{
		log(enableLog,processName+" started");
		
		final ConcurrentHashMap<Integer, Boolean> completedMap = new ConcurrentHashMap<>();
		
		try {
			for (int i=0; i<parallelProcessList.size(); i++) {			
				Runnable step = parallelProcessList.get(i);
				log(enableLog,processName+" queueing step "+i);
				final int stepId=i;
				ThreadUtil.addTask(() -> {
					step.run();
					completedMap.put(stepId, true);
					// System.out.println("Step "+stepId+" has completed");
				});
			}
			
			boolean waiting=true;
			
			while (waiting) {				
				if (completedMap.size()==parallelProcessList.size())
				{
					waiting=false;
				}
				
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					
				}
			}
			
			lastProcessed = parallelProcessList;
			log(enableLog,processName+" finished successfully"); // Causing JVM to exit for some reason
			return new ProcessComplete(true, true);
		} catch (Exception e) {
			return new ProcessComplete(true, false);
		}		
	}
}

Commenting out

log(enableLog,processName+" finished successfully"); // Causing JVM to exit for some reason

to

// log(enableLog,processName+" finished successfully"); // Causing JVM to exit for some reason

Seems to allow the process to continue

Reproducible bug, might be specific to Java 19, I have Preview Features Enabled which might factor into it

Less bugs in Multithreaded Runtimes can lead to more ability to utilize Multithreading Worldwide

When that log line is commented out I get the following output:

....
Computed iterations: 200000000
Computed iterations: 210000000
Computed iterations: 210000000
Computed iterations: 210000000
Computed iterations: 210000000
Computed iterations: 220000000
Computed iterations: 220000000
Computed iterations: 220000000
Computed iterations: 220000000
Computed iterations: 230000000
Computed iterations: 230000000
Computed iterations: 230000000
Computed iterations: 230000000
Computed iterations: 240000000
Computed iterations: 240000000
Computed iterations: 240000000
Computed iterations: 240000000
process complete successful
Sine from LazyLoadedMathUtil for 4*250 million calls: 151531 ms

From the looks of this loops with large amounts of HashMap calls can likely be sped up via multithreading

Father please increase render cycles and speed of HashMaps for all people not limiting my families finances In Christ’s name I ask this

Published by techinfodebug

Flex and Java Developer, Christian, Art, Music, Video, and Vlogging

Leave a comment