├── .gitignore ├── .pre-commit-config.yaml ├── Assignment1 ├── Assignment1.iml └── src │ └── com │ └── assignment │ ├── part1 │ ├── Ball.java │ ├── BallThread.java │ ├── BounceFrame.java │ ├── Main.java │ ├── ObjectCanvas.java │ ├── Pool.java │ ├── Score.java │ ├── ScoreListener.java │ └── ScoreThread.java │ ├── part2 │ ├── Control.java │ ├── Main.java │ ├── PrintThread1.java │ └── PrintThread2.java │ └── part3 │ ├── Counter.java │ └── Main.java ├── Assignment2 ├── Assignment2.iml └── src │ └── com │ └── assignment │ ├── Algorithm.java │ ├── Main.java │ ├── basic │ └── BasicAlgorithm.java │ ├── fox │ ├── FoxAlgorithm.java │ └── FoxAlgorithmThread.java │ ├── striped │ ├── StripedAlgorithm.java │ ├── StripedAlgorithmCallable.java │ ├── StripedAlgorithmCallable2.java │ ├── StripedAlgorithmThread.java │ └── StripedAlgorithmThread2.java │ └── utils │ └── Matrix.java ├── Assignment3 ├── Assignment3.iml └── src │ └── com │ └── assignment │ ├── task1 │ ├── Bank.java │ ├── Main.java │ └── TransferThread.java │ ├── task2 │ ├── Consumer.java │ ├── Drop.java │ ├── Main.java │ └── Producer.java │ └── task3 │ ├── Group.java │ ├── Journal.java │ ├── Main.java │ └── Teacher.java ├── Assignment4 ├── Assignment4.iml ├── out │ └── production │ │ └── Assignment4 │ │ ├── Assignment4.iml │ │ ├── commonWords │ │ ├── 1.txt │ │ └── 2.txt │ │ ├── keyWords │ │ ├── 1.txt │ │ ├── 2.txt │ │ └── 3.txt │ │ ├── resources │ │ ├── commonWords │ │ │ ├── 1.txt │ │ │ └── 2.txt │ │ ├── keyWords │ │ │ ├── 1.txt │ │ │ ├── 2.txt │ │ │ └── 3.txt │ │ └── text.txt │ │ ├── src │ │ └── com │ │ │ └── assignment │ │ │ ├── task1 │ │ │ ├── ForkJoinWordCount.java │ │ │ ├── Main.java │ │ │ ├── SimpleWordCount.java │ │ │ └── TextLoader.java │ │ │ ├── task2 │ │ │ ├── Algorithm.java │ │ │ ├── Main.java │ │ │ ├── basic │ │ │ │ └── BasicAlgorithm.java │ │ │ ├── fox │ │ │ │ ├── FoxAlgorithm.java │ │ │ │ └── FoxAlgorithmForkJoin.java │ │ │ └── utils │ │ │ │ └── Matrix.java │ │ │ ├── task3 │ │ │ ├── Document.java │ │ │ ├── DocumentSearchTask.java │ │ │ ├── Folder.java │ │ │ ├── FolderSearchTask.java │ │ │ ├── Main.java │ │ │ └── WordCounter.java │ │ │ └── task4 │ │ │ ├── Document.java │ │ │ ├── DocumentSearchTask.java │ │ │ ├── Folder.java │ │ │ ├── FolderSearchTask.java │ │ │ ├── Main.java │ │ │ └── WordCounter.java │ │ └── text.txt ├── resources │ ├── commonWords │ │ ├── 1.txt │ │ └── 2.txt │ ├── keyWords │ │ ├── 1.txt │ │ ├── 2.txt │ │ └── 3.txt │ └── text.txt └── src │ └── com │ └── assignment │ ├── task1 │ ├── ForkJoinWordCount.java │ ├── Main.java │ ├── SimpleWordCount.java │ └── TextLoader.java │ ├── task2 │ ├── Algorithm.java │ ├── Main.java │ ├── basic │ │ └── BasicAlgorithm.java │ ├── fox │ │ ├── FoxAlgorithm.java │ │ └── FoxAlgorithmForkJoin.java │ └── utils │ │ └── Matrix.java │ ├── task3 │ ├── Document.java │ ├── DocumentSearchTask.java │ ├── Folder.java │ ├── FolderSearchTask.java │ ├── Main.java │ └── WordCounter.java │ └── task4 │ ├── Document.java │ ├── DocumentSearchTask.java │ ├── Folder.java │ ├── FolderSearchTask.java │ ├── Main.java │ └── WordCounter.java ├── Assignment5 ├── Assignment5.iml └── src │ └── com │ └── assignment │ ├── Create.java │ ├── Element.java │ ├── FunRand.java │ ├── Model.java │ ├── Process.java │ └── SimModel.java ├── Assignment6 ├── CMakeLists.txt ├── Makefile ├── hostfile └── src │ ├── task1 │ └── main.cpp │ └── task2 │ └── main.cpp ├── AssignmentsList.pdf ├── LICENSE ├── Makefile ├── README.md └── mpj-examples ├── HelloWorldParallel.java ├── MatrixMul4.java ├── MatrixMul8.java ├── MultiplyMatrixToVector.java ├── MultiplyVectorToScalar.java ├── TestAllGather.java ├── TestAllGatherv.java ├── TestAllReduce.java ├── TestAllToAll.java ├── TestAllToAllv.java ├── TestBcast.java ├── TestCreateIntracomm.java ├── TestGather.java ├── TestGatherv.java ├── TestISendAndIRecv.java ├── TestProbe.java ├── TestReduce.java ├── TestReduceScatter.java ├── TestScan.java ├── TestScatter.java ├── TestScatterv.java ├── TestSendAndRecv.java └── Transport.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | # idea files 26 | .idea 27 | 28 | # VScode 29 | .vscode 30 | 31 | # Prerequisites 32 | *.d 33 | 34 | # Compiled Object files 35 | *.slo 36 | *.lo 37 | *.o 38 | *.obj 39 | 40 | # Precompiled Headers 41 | *.gch 42 | *.pch 43 | 44 | # Compiled Dynamic libraries 45 | *.so 46 | *.dylib 47 | *.dll 48 | 49 | # Fortran module files 50 | *.mod 51 | *.smod 52 | 53 | # Compiled Static libraries 54 | *.lai 55 | *.la 56 | *.a 57 | *.lib 58 | 59 | # Executables 60 | *.exe 61 | *.out 62 | *.app 63 | 64 | # IntelliJ 65 | out/ 66 | 67 | # CMake 68 | cmake-build-*/ 69 | 70 | # os 71 | os 72 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/macisamuele/language-formatters-pre-commit-hooks 3 | rev: v1.6.1 4 | hooks: 5 | - id: pretty-format-java 6 | args: [--autofix] 7 | - id: pretty-format-yaml 8 | args: [--autofix, --indent, '2'] 9 | - repo: https://github.com/bmorcos/pre-commit-hooks-cpp 10 | rev: master 11 | hooks: 12 | - id: clang-format 13 | - id: cppcheck 14 | -------------------------------------------------------------------------------- /Assignment1/Assignment1.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Assignment1/src/com/assignment/part1/Ball.java: -------------------------------------------------------------------------------- 1 | package com.assignment.part1; 2 | 3 | import java.awt.*; 4 | import java.awt.geom.Ellipse2D; 5 | import java.util.Random; 6 | 7 | class Ball { 8 | private final Component canvas; 9 | private static final int RADIUS = 10; 10 | private static final int DIAMETER = RADIUS * 2; 11 | private int x = 0; 12 | private int y = 0; 13 | private int dx = 2; 14 | private int dy = 2; 15 | private final Color color; 16 | public boolean isInPool = false; 17 | 18 | public Ball(Component c, Color color) { 19 | this.canvas = c; 20 | this.color = color; 21 | 22 | if (Math.random() < 0.5) { 23 | x = new Random().nextInt(this.canvas.getWidth()); 24 | y = 0; 25 | } else { 26 | x = 0; 27 | y = new Random().nextInt(this.canvas.getHeight()); 28 | } 29 | } 30 | 31 | public Ball(Component c, Color color, int x, int y) { 32 | this.canvas = c; 33 | this.color = color; 34 | 35 | this.x = x; 36 | this.y = y; 37 | } 38 | 39 | public static void f() { 40 | int a = 0; 41 | } 42 | 43 | public void draw(Graphics2D g2) { 44 | g2.setColor(this.color); 45 | g2.fill(new Ellipse2D.Double(x, y, DIAMETER, DIAMETER)); 46 | } 47 | 48 | public void move() { 49 | x += dx; 50 | y += dy; 51 | if (x < 0) { 52 | x = 0; 53 | dx = -dx; 54 | } 55 | if (x + DIAMETER >= this.canvas.getWidth()) { 56 | x = this.canvas.getWidth() - DIAMETER; 57 | dx = -dx; 58 | } 59 | 60 | if (y < 0) { 61 | y = 0; 62 | dy = -dy; 63 | } 64 | if (y + DIAMETER >= this.canvas.getHeight()) { 65 | y = this.canvas.getHeight() - DIAMETER; 66 | dy = -dy; 67 | } 68 | 69 | this.canvas.revalidate(); 70 | this.canvas.repaint(); 71 | } 72 | 73 | public boolean isInPool(Pool pool) { 74 | double distance = 75 | Math.sqrt(Math.pow(pool.getX() - this.x, 2) + Math.pow(pool.getY() - this.y, 2)); 76 | 77 | return distance + RADIUS < Pool.getRADIUS(); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /Assignment1/src/com/assignment/part1/BallThread.java: -------------------------------------------------------------------------------- 1 | package com.assignment.part1; 2 | 3 | import javax.swing.*; 4 | 5 | public class BallThread extends Thread { 6 | private final Ball ball; 7 | private int TIME = 10000; 8 | 9 | public BallThread(Ball ball) { 10 | this.ball = ball; 11 | } 12 | 13 | @Override 14 | public void run() { 15 | try { 16 | for (int i = 1; (i < TIME) & (!Thread.currentThread().isInterrupted()); i++) { 17 | 18 | ball.move(); 19 | 20 | if (ball.isInPool) { 21 | // Thread.currentThread().interrupt(); 22 | break; 23 | } 24 | 25 | System.out.println("Thread name = " + Thread.currentThread().getName()); 26 | Thread.sleep(5); 27 | } 28 | } catch (InterruptedException ignored) { 29 | System.out.println("Thread " + Thread.currentThread().getName() + " was interrupted!"); 30 | } 31 | } 32 | 33 | public void setTIME(int TIME) { 34 | this.TIME = TIME; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Assignment1/src/com/assignment/part1/BounceFrame.java: -------------------------------------------------------------------------------- 1 | package com.assignment.part1; 2 | 3 | import java.awt.*; 4 | import java.awt.event.ActionEvent; 5 | import java.awt.event.ActionListener; 6 | import javax.swing.*; 7 | 8 | public class BounceFrame extends JFrame { 9 | private final ObjectCanvas canvas; 10 | private static final int N_BLUE_BALLS = 1000; 11 | private static final int N_RED_BALLS = 1; 12 | private static final int N_JOIN_EXPERIMENT = 10; 13 | public static final int WIDTH = 850; 14 | public static final int HEIGHT = 750; 15 | 16 | public BounceFrame() { 17 | 18 | this.setSize(WIDTH, HEIGHT); 19 | this.setTitle("Bounce program"); 20 | this.canvas = new ObjectCanvas(); 21 | 22 | Pool p1 = new Pool(canvas, Color.CYAN, 0, 0); 23 | canvas.add(p1); 24 | Pool p2 = new Pool(canvas, Color.CYAN, WIDTH, 0); 25 | canvas.add(p2); 26 | Pool p3 = new Pool(canvas, Color.CYAN, 0, HEIGHT - 100); 27 | canvas.add(p3); 28 | Pool p4 = new Pool(canvas, Color.CYAN, WIDTH, HEIGHT - 100); 29 | canvas.add(p4); 30 | 31 | System.out.println( 32 | new StringBuilder() 33 | .append("In Frame Thread name = ") 34 | .append(Thread.currentThread().getName()) 35 | .toString()); 36 | 37 | Container content = this.getContentPane(); 38 | content.add(this.canvas, BorderLayout.CENTER); 39 | 40 | JPanel buttonPanel = new JPanel(); 41 | buttonPanel.setBackground(Color.lightGray); 42 | 43 | JPanel labelPanel = new JPanel(); 44 | labelPanel.setBackground(Color.lightGray); 45 | 46 | JButton buttonAddBlueBall = new JButton("Add blue ball"); 47 | JButton buttonAddRedBall = new JButton("Add red ball"); 48 | JButton buttonPriorityExperiment = new JButton("Red/Blue priority experiment"); 49 | JButton buttonJoinExperiment = new JButton("Join experiment"); 50 | JButton buttonStop = new JButton("Stop"); 51 | 52 | JLabel labelScore = new JLabel("Score: " + Score.getScore()); 53 | /* 54 | // also, we can use daemon thread 55 | 56 | ScoreThread scoreThreadad = new ScoreThread(labelScore); 57 | scoreThreadad.setDaemon(true); 58 | scoreThreadad.setPriority(Thread.MAX_PRIORITY); 59 | scoreThreadad.start(); 60 | */ 61 | 62 | Score.addListener( 63 | new ScoreListener() { 64 | @Override 65 | public void actionPerformed() { 66 | labelScore.setText("Score: " + Score.getScore()); 67 | labelScore.repaint(); 68 | } 69 | }); 70 | 71 | buttonAddBlueBall.addActionListener( 72 | new ActionListener() { 73 | @Override 74 | public void actionPerformed(ActionEvent e) { 75 | Color color = Color.BLUE; 76 | createBall(color, Thread.NORM_PRIORITY); 77 | } 78 | }); 79 | 80 | buttonAddRedBall.addActionListener( 81 | new ActionListener() { 82 | @Override 83 | public void actionPerformed(ActionEvent e) { 84 | Color color = Color.RED; 85 | createBall(color, Thread.NORM_PRIORITY); 86 | } 87 | }); 88 | 89 | buttonPriorityExperiment.addActionListener( 90 | new ActionListener() { 91 | @Override 92 | public void actionPerformed(ActionEvent e) { 93 | createPriorityExperiment(); 94 | } 95 | }); 96 | 97 | buttonJoinExperiment.addActionListener( 98 | new ActionListener() { 99 | @Override 100 | public void actionPerformed(ActionEvent e) { 101 | Runnable updatePanel = 102 | new Runnable() { 103 | public void run() { 104 | createJoinExperiment(); 105 | } 106 | }; 107 | Thread t = new Thread(updatePanel); 108 | t.start(); 109 | } 110 | }); 111 | 112 | buttonStop.addActionListener( 113 | new ActionListener() { 114 | @Override 115 | public void actionPerformed(ActionEvent e) { 116 | 117 | System.exit(0); 118 | } 119 | }); 120 | 121 | buttonPanel.add(buttonAddBlueBall); 122 | buttonPanel.add(buttonAddRedBall); 123 | buttonPanel.add(buttonPriorityExperiment); 124 | buttonPanel.add(buttonJoinExperiment); 125 | buttonPanel.add(buttonStop); 126 | 127 | labelPanel.add(labelScore); 128 | 129 | content.add(buttonPanel, BorderLayout.SOUTH); 130 | content.add(labelPanel, BorderLayout.NORTH); 131 | } 132 | 133 | private void createBall(Color color, int priority) { 134 | Ball b = new Ball(canvas, color); 135 | canvas.add(b); 136 | 137 | BallThread thread = new BallThread(b); 138 | thread.setPriority(priority); 139 | thread.start(); 140 | 141 | System.out.println("Thread name = " + thread.getName()); 142 | } 143 | 144 | private void createBall(Color color, int priority, int x, int y) { 145 | Ball b = new Ball(canvas, color, x, y); 146 | canvas.add(b); 147 | 148 | BallThread thread = new BallThread(b); 149 | thread.setPriority(priority); 150 | thread.start(); 151 | 152 | System.out.println("Thread name = " + thread.getName()); 153 | } 154 | 155 | private void createBall(Color color, int priority, int x, int y, int TIME) { 156 | Ball b = new Ball(canvas, color, x, y); 157 | canvas.add(b); 158 | 159 | BallThread thread = new BallThread(b); 160 | thread.setTIME(TIME); 161 | thread.setPriority(priority); 162 | thread.start(); 163 | 164 | try { 165 | thread.join(); 166 | } catch (InterruptedException e) { 167 | e.printStackTrace(); 168 | } 169 | 170 | System.out.println("Thread name = " + thread.getName()); 171 | } 172 | 173 | private void createPriorityExperiment() { 174 | Color color = Color.BLUE; 175 | for (int i = 0; i < N_BLUE_BALLS; i++) { 176 | createBall(color, 1, WIDTH / 2, HEIGHT / 2); 177 | } 178 | 179 | color = Color.RED; 180 | for (int i = 0; i < N_RED_BALLS; i++) { 181 | createBall(color, 10, WIDTH / 2, HEIGHT / 2); 182 | } 183 | } 184 | 185 | private void createJoinExperiment() { 186 | int TIME = 1000; 187 | 188 | for (int i = 0; i < N_JOIN_EXPERIMENT; i++) { 189 | Color color; 190 | if (i % 2 == 0) { 191 | color = Color.BLUE; 192 | } else { 193 | color = Color.RED; 194 | } 195 | createBall(color, Thread.MIN_PRIORITY, WIDTH / 2, HEIGHT / 2, TIME); 196 | } 197 | } 198 | } 199 | -------------------------------------------------------------------------------- /Assignment1/src/com/assignment/part1/Main.java: -------------------------------------------------------------------------------- 1 | package com.assignment.part1; 2 | 3 | import javax.swing.*; 4 | 5 | public class Main { 6 | 7 | public static void main(String[] args) { 8 | BounceFrame frame = new BounceFrame(); 9 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 10 | 11 | frame.setVisible(true); 12 | System.out.println("Thread name = " + Thread.currentThread().getName()); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Assignment1/src/com/assignment/part1/ObjectCanvas.java: -------------------------------------------------------------------------------- 1 | package com.assignment.part1; 2 | 3 | import java.awt.*; 4 | import java.util.ArrayList; 5 | import javax.swing.*; 6 | 7 | public class ObjectCanvas extends JPanel { 8 | private final ArrayList balls = new ArrayList<>(); 9 | private final ArrayList pools = new ArrayList<>(); 10 | 11 | public void add(Ball b) { 12 | this.balls.add(b); 13 | } 14 | 15 | public void add(Pool p) { 16 | this.pools.add(p); 17 | } 18 | 19 | public void remove(Ball b) { 20 | Score.increase(); 21 | this.balls.remove(b); 22 | } 23 | 24 | @Override 25 | public void paintComponent(Graphics g) { 26 | super.paintComponent(g); 27 | Graphics2D g2 = (Graphics2D) g; 28 | 29 | try { 30 | for (Ball b : balls) { 31 | for (Pool p : pools) { 32 | if (b.isInPool(p)) { 33 | b.isInPool = true; 34 | remove(b); 35 | break; 36 | } 37 | } 38 | if (!b.isInPool) { 39 | b.draw(g2); 40 | } 41 | } 42 | } catch (Exception ignored) { 43 | } 44 | 45 | for (Pool p : pools) { 46 | p.draw(g2); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Assignment1/src/com/assignment/part1/Pool.java: -------------------------------------------------------------------------------- 1 | package com.assignment.part1; 2 | 3 | import java.awt.*; 4 | import java.awt.geom.Ellipse2D; 5 | 6 | public class Pool { 7 | private final Component canvas; 8 | private static final int RADIUS = 40; 9 | private static final int DIAMETER = RADIUS * 2; 10 | private int x = 0; 11 | private int y = 0; 12 | private final Color color; 13 | 14 | public Pool(Component c, Color color) { 15 | this.canvas = c; 16 | this.color = color; 17 | } 18 | 19 | public Pool(Component c, Color color, int x, int y) { 20 | this.canvas = c; 21 | this.color = color; 22 | this.x = x; 23 | this.y = y; 24 | } 25 | 26 | public static void f() { 27 | int a = 0; 28 | } 29 | 30 | public void draw(Graphics2D g2) { 31 | g2.setColor(this.color); 32 | g2.fill(new Ellipse2D.Double(x - RADIUS, y - RADIUS, DIAMETER, DIAMETER)); 33 | } 34 | 35 | public int getX() { 36 | return x; 37 | } 38 | 39 | public int getY() { 40 | return y; 41 | } 42 | 43 | public static int getRADIUS() { 44 | return RADIUS; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Assignment1/src/com/assignment/part1/Score.java: -------------------------------------------------------------------------------- 1 | package com.assignment.part1; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Score { 7 | private static int score = 0; 8 | 9 | private static final List listeners = new ArrayList(); 10 | 11 | public static void addListener(ScoreListener toAdd) { 12 | listeners.add(toAdd); 13 | } 14 | 15 | public static void increase() { 16 | Score.score += 1; 17 | 18 | // Notify everybody that may be interested. 19 | for (ScoreListener hl : listeners) hl.actionPerformed(); 20 | } 21 | 22 | public static int getScore() { 23 | return score; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Assignment1/src/com/assignment/part1/ScoreListener.java: -------------------------------------------------------------------------------- 1 | package com.assignment.part1; 2 | 3 | public interface ScoreListener { 4 | void actionPerformed(); 5 | } 6 | -------------------------------------------------------------------------------- /Assignment1/src/com/assignment/part1/ScoreThread.java: -------------------------------------------------------------------------------- 1 | package com.assignment.part1; 2 | 3 | import javax.swing.*; 4 | 5 | public class ScoreThread extends Thread { 6 | private final JLabel label; 7 | 8 | public ScoreThread(JLabel label) { 9 | this.label = label; 10 | } 11 | 12 | @Override 13 | public void run() { 14 | System.out.println("Daemon thread name = " + Thread.currentThread().getName()); 15 | while (!Thread.currentThread().isInterrupted()) { 16 | label.setText("Score: " + Score.getScore()); 17 | label.repaint(); 18 | try { 19 | Thread.sleep(5); 20 | } catch (InterruptedException ignored) { 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Assignment1/src/com/assignment/part2/Control.java: -------------------------------------------------------------------------------- 1 | package com.assignment.part2; 2 | 3 | public class Control { 4 | public volatile boolean flag = false; 5 | } 6 | -------------------------------------------------------------------------------- /Assignment1/src/com/assignment/part2/Main.java: -------------------------------------------------------------------------------- 1 | package com.assignment.part2; 2 | 3 | public class Main { 4 | public static void main(String[] args) throws InterruptedException { 5 | Runnable task1 = 6 | () -> { 7 | System.out.println("Part 5.1:"); 8 | run51(); 9 | }; 10 | Thread taskThread1 = new Thread(task1); 11 | taskThread1.start(); 12 | taskThread1.join(); 13 | 14 | Thread.sleep(10); 15 | 16 | Runnable task2 = 17 | () -> { 18 | System.out.println("\nPart 5.2:"); 19 | run52(); 20 | }; 21 | Thread taskThread2 = new Thread(task2); 22 | taskThread2.start(); 23 | taskThread2.join(); 24 | } 25 | 26 | public static void run51() { 27 | PrintThread1 p1 = new PrintThread1("-"); 28 | PrintThread1 p2 = new PrintThread1("|"); 29 | 30 | Thread t1 = new Thread(p1); 31 | Thread t2 = new Thread(p2); 32 | 33 | t1.start(); 34 | t2.start(); 35 | } 36 | 37 | public static void run52() { 38 | Control control = new Control(); 39 | PrintThread2 p1 = new PrintThread2("-", control); 40 | PrintThread2 p2 = new PrintThread2("|", control); 41 | 42 | p1.start(); 43 | p2.start(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Assignment1/src/com/assignment/part2/PrintThread1.java: -------------------------------------------------------------------------------- 1 | package com.assignment.part2; 2 | 3 | public class PrintThread1 implements Runnable { 4 | private String text = ""; 5 | private final int n_max = 500; 6 | 7 | public PrintThread1(String text) { 8 | this.text = text; 9 | } 10 | 11 | @Override 12 | public void run() { 13 | for (int i = 0; i < n_max; i++) { 14 | System.out.print(this.text); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Assignment1/src/com/assignment/part2/PrintThread2.java: -------------------------------------------------------------------------------- 1 | package com.assignment.part2; 2 | 3 | public class PrintThread2 extends Thread { 4 | private String text = ""; 5 | private final Control control; 6 | private final int n_max = 500; 7 | 8 | public PrintThread2(String text, Control control) { 9 | this.text = text; 10 | this.control = control; 11 | } 12 | 13 | @Override 14 | public void run() { 15 | synchronized (control) { 16 | for (int i = 0; i < n_max; i++) { 17 | while (control.flag && this.text.equals("-")) { 18 | try { 19 | control.wait(); 20 | } catch (InterruptedException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | 25 | while (!control.flag && this.text.equals("|")) { 26 | try { 27 | control.wait(); 28 | } catch (InterruptedException e) { 29 | e.printStackTrace(); 30 | } 31 | } 32 | 33 | System.out.print(this.text); 34 | control.flag = !control.flag; 35 | control.notifyAll(); 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Assignment1/src/com/assignment/part3/Counter.java: -------------------------------------------------------------------------------- 1 | package com.assignment.part3; 2 | 3 | public class Counter { 4 | private int count = 0; 5 | 6 | public void incrementUnsynchronized() { 7 | count++; 8 | } 9 | 10 | public void decrementUnsynchronized() { 11 | count--; 12 | } 13 | 14 | public synchronized void incrementSynchronizedMethod() { 15 | count++; 16 | } 17 | 18 | public synchronized void decrementSynchronizedMethod() { 19 | count--; 20 | } 21 | 22 | public void incrementSynchronizedBlock() { 23 | synchronized (this) { 24 | count++; 25 | } 26 | } 27 | 28 | public void decrementSynchronizedBlock() { 29 | synchronized (this) { 30 | count--; 31 | } 32 | } 33 | 34 | public int getCount() { 35 | return count; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Assignment1/src/com/assignment/part3/Main.java: -------------------------------------------------------------------------------- 1 | package com.assignment.part3; 2 | 3 | import java.util.concurrent.locks.ReentrantLock; 4 | 5 | public class Main { 6 | public static void main(String[] args) throws InterruptedException { 7 | Counter counter1 = new Counter(); 8 | 9 | Runnable part61 = 10 | () -> { 11 | run61(counter1); 12 | }; 13 | Thread part61Thread = new Thread(part61); 14 | 15 | part61Thread.start(); 16 | part61Thread.join(); 17 | 18 | System.out.println("Counter for part 6.1 = " + counter1.getCount()); 19 | 20 | Counter counter2 = new Counter(); 21 | 22 | Runnable part62 = 23 | () -> { 24 | try { 25 | run62(counter2); 26 | } catch (InterruptedException e) { 27 | e.printStackTrace(); 28 | } 29 | }; 30 | Thread part62Thread = new Thread(part62); 31 | 32 | part62Thread.start(); 33 | part62Thread.join(); 34 | 35 | System.out.println("Counter for part 6.2 = " + counter2.getCount()); 36 | 37 | Counter counter3 = new Counter(); 38 | 39 | Runnable part63 = 40 | () -> { 41 | try { 42 | run63(counter3); 43 | } catch (InterruptedException e) { 44 | e.printStackTrace(); 45 | } 46 | }; 47 | Thread part63Thread = new Thread(part63); 48 | 49 | part63Thread.start(); 50 | part63Thread.join(); 51 | 52 | System.out.println("Counter for part 6.3 = " + counter3.getCount()); 53 | 54 | Counter counter4 = new Counter(); 55 | 56 | Runnable part64 = 57 | () -> { 58 | try { 59 | run64(counter4); 60 | } catch (InterruptedException e) { 61 | e.printStackTrace(); 62 | } 63 | }; 64 | Thread part64Thread = new Thread(part64); 65 | 66 | part64Thread.start(); 67 | part64Thread.join(); 68 | 69 | System.out.println("Counter for part 6.4 = " + counter4.getCount()); 70 | } 71 | 72 | public static void run61(Counter counter) { 73 | int n_times = 1_000_000; 74 | 75 | Runnable task1 = 76 | () -> { 77 | for (int i = 0; i < n_times; i++) counter.incrementUnsynchronized(); 78 | }; 79 | Thread taskThread1 = new Thread(task1); 80 | 81 | Runnable task2 = 82 | () -> { 83 | for (int i = 0; i < n_times; i++) counter.decrementUnsynchronized(); 84 | }; 85 | Thread taskThread2 = new Thread(task2); 86 | 87 | taskThread1.start(); 88 | taskThread2.start(); 89 | } 90 | 91 | public static void run62(Counter counter) throws InterruptedException { 92 | int n_times = 1_000_000; 93 | 94 | Runnable task1 = 95 | () -> { 96 | for (int i = 0; i < n_times; i++) counter.incrementSynchronizedMethod(); 97 | }; 98 | Thread taskThread1 = new Thread(task1); 99 | 100 | Runnable task2 = 101 | () -> { 102 | for (int i = 0; i < n_times; i++) counter.decrementSynchronizedMethod(); 103 | }; 104 | Thread taskThread2 = new Thread(task2); 105 | 106 | taskThread1.start(); 107 | taskThread2.start(); 108 | 109 | taskThread1.join(); 110 | taskThread2.join(); 111 | } 112 | 113 | public static void run63(Counter counter) throws InterruptedException { 114 | int n_times = 1_000_000; 115 | 116 | Runnable task1 = 117 | () -> { 118 | for (int i = 0; i < n_times; i++) counter.incrementSynchronizedBlock(); 119 | }; 120 | Thread taskThread1 = new Thread(task1); 121 | 122 | Runnable task2 = 123 | () -> { 124 | for (int i = 0; i < n_times; i++) counter.decrementSynchronizedBlock(); 125 | }; 126 | Thread taskThread2 = new Thread(task2); 127 | 128 | taskThread1.start(); 129 | taskThread2.start(); 130 | 131 | taskThread1.join(); 132 | taskThread2.join(); 133 | } 134 | 135 | public static void run64(Counter counter) throws InterruptedException { 136 | int n_times = 1_000_000; 137 | 138 | ReentrantLock lock = new ReentrantLock(); 139 | 140 | Runnable task1 = 141 | () -> { 142 | for (int i = 0; i < n_times; i++) { 143 | lock.lock(); 144 | counter.incrementUnsynchronized(); 145 | lock.unlock(); 146 | } 147 | }; 148 | Thread taskThread1 = new Thread(task1); 149 | 150 | Runnable task2 = 151 | () -> { 152 | for (int i = 0; i < n_times; i++) { 153 | lock.lock(); 154 | counter.decrementUnsynchronized(); 155 | lock.unlock(); 156 | } 157 | }; 158 | Thread taskThread2 = new Thread(task2); 159 | 160 | taskThread1.start(); 161 | taskThread2.start(); 162 | 163 | taskThread1.join(); 164 | taskThread2.join(); 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /Assignment2/Assignment2.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Assignment2/src/com/assignment/Algorithm.java: -------------------------------------------------------------------------------- 1 | package com.assignment; 2 | 3 | import com.assignment.utils.Matrix; 4 | 5 | public interface Algorithm { 6 | public Matrix multiply(); 7 | } 8 | -------------------------------------------------------------------------------- /Assignment2/src/com/assignment/Main.java: -------------------------------------------------------------------------------- 1 | package com.assignment; 2 | 3 | import com.assignment.basic.BasicAlgorithm; 4 | import com.assignment.fox.FoxAlgorithm; 5 | import com.assignment.striped.StripedAlgorithm; 6 | import com.assignment.utils.Matrix; 7 | import java.util.HashMap; 8 | import java.util.List; 9 | import java.util.Map; 10 | import java.util.stream.Collectors; 11 | 12 | public class Main { 13 | public static void main(String[] args) { 14 | simpleRun(false); 15 | // threadNExperiment(); 16 | // sizeMatrixExperiment(); 17 | } 18 | 19 | public static void simpleRun(boolean printMatrices) { 20 | int sizeAxis0 = 2000; 21 | int sizeAxis1 = 2000; 22 | 23 | Matrix A = new Matrix(sizeAxis0, sizeAxis1); 24 | Matrix B = new Matrix(sizeAxis0, sizeAxis1); 25 | 26 | A.generateRandomMatrix(); 27 | B.generateRandomMatrix(); 28 | 29 | // A.matrix = new double[][] {{1.1, 1, 1}, {2, 2.1, 2}, {3, 3, 3}}; 30 | // B.matrix = new double[][] {{1, 1, 1}, {2, 5, 2}, {3, 3, 3}}; 31 | 32 | int nThread = Runtime.getRuntime().availableProcessors(); // sizeAxis0 33 | 34 | BasicAlgorithm ba = new BasicAlgorithm(A, B); 35 | StripedAlgorithm sa = new StripedAlgorithm(A, B, nThread); 36 | FoxAlgorithm fa = new FoxAlgorithm(A, B, nThread); 37 | 38 | long currTime = System.nanoTime(); 39 | Matrix C = ba.multiply(); 40 | currTime = System.nanoTime() - currTime; 41 | 42 | if (printMatrices) C.print(); 43 | 44 | System.out.println("Time for Basic Algorithm: " + currTime / 1_000_000); 45 | 46 | currTime = System.nanoTime(); 47 | C = sa.multiply(); 48 | currTime = System.nanoTime() - currTime; 49 | 50 | if (printMatrices) C.print(); 51 | 52 | System.out.println("Time for Striped Algorithm: " + currTime / 1_000_000); 53 | 54 | currTime = System.nanoTime(); 55 | C = fa.multiply(); 56 | currTime = System.nanoTime() - currTime; 57 | 58 | if (printMatrices) C.print(); 59 | 60 | System.out.println("Time for Fox Algorithm: " + currTime / 1_000_000); 61 | System.out.println("\n"); 62 | } 63 | 64 | public static void threadNExperiment() { 65 | int sizeAxis0 = 1000; 66 | int sizeAxis1 = 1000; 67 | int nExperiments = 3; 68 | 69 | int[] threadsNStriped = new int[] {5, 10, 50, 100, 500, 1000}; 70 | int[] threadsNFox = new int[] {4, 5, 10, 25, 50, 75}; 71 | Map timeResultStriped = new HashMap<>(); 72 | Map timeResultFox = new HashMap<>(); 73 | 74 | Matrix A = new Matrix(sizeAxis0, sizeAxis1); 75 | Matrix B = new Matrix(sizeAxis0, sizeAxis1); 76 | 77 | A.generateRandomMatrix(); 78 | B.generateRandomMatrix(); 79 | 80 | for (int nThread : threadsNStriped) { 81 | StripedAlgorithm sa = new StripedAlgorithm(A, B, nThread); 82 | 83 | long acc = 0; 84 | for (int i = 0; i < nExperiments; i++) { 85 | long currTime = System.nanoTime(); 86 | Matrix C = sa.multiply(); 87 | acc += System.nanoTime() - currTime; 88 | } 89 | acc /= nExperiments; 90 | 91 | timeResultStriped.put(nThread, acc / 1_000_000); 92 | } 93 | 94 | for (int nThread : threadsNFox) { 95 | FoxAlgorithm fa = new FoxAlgorithm(A, B, nThread); 96 | 97 | long acc = 0; 98 | for (int i = 0; i < nExperiments; i++) { 99 | long currTime = System.nanoTime(); 100 | Matrix C = fa.multiply(); 101 | acc += System.nanoTime() - currTime; 102 | } 103 | acc /= nExperiments; 104 | 105 | timeResultFox.put(nThread, acc / 1_000_000); 106 | } 107 | 108 | List keysStriped = 109 | timeResultStriped.keySet().stream().sorted().collect(Collectors.toList()); 110 | 111 | System.out.println("**Number of threads experiment (Striped)**"); 112 | 113 | System.out.printf("%30s", "Number of thread:"); 114 | for (int key : keysStriped) { 115 | System.out.printf("%10d", key); 116 | System.out.print(" "); 117 | } 118 | 119 | System.out.println(); 120 | 121 | System.out.printf("%30s", "Time:"); 122 | for (int key : keysStriped) { 123 | System.out.printf("%10d", timeResultStriped.get(key)); 124 | System.out.print(" "); 125 | } 126 | System.out.println("\n"); 127 | 128 | List keysFox = timeResultFox.keySet().stream().sorted().collect(Collectors.toList()); 129 | 130 | System.out.println("**Number of threads experiment (Fox)**"); 131 | 132 | System.out.printf("%30s", "Number of thread:"); 133 | for (int key : keysFox) { 134 | System.out.printf("%10d", key); 135 | System.out.print(" "); 136 | } 137 | 138 | System.out.println(); 139 | 140 | System.out.printf("%30s", "Time:"); 141 | for (int key : keysFox) { 142 | System.out.printf("%10d", timeResultFox.get(key)); 143 | System.out.print(" "); 144 | } 145 | System.out.println("\n"); 146 | } 147 | 148 | public static void sizeMatrixExperiment() { 149 | int nThread = Runtime.getRuntime().availableProcessors(); 150 | int nExperiments = 3; 151 | 152 | int[] sizesArray = new int[] {10, 100, 500, 1000, 1500}; 153 | Map timeResultStriped = new HashMap<>(); 154 | Map timeResultFox = new HashMap<>(); 155 | 156 | for (int size : sizesArray) { 157 | Matrix A = new Matrix(size, size); 158 | Matrix B = new Matrix(size, size); 159 | 160 | A.generateRandomMatrix(); 161 | B.generateRandomMatrix(); 162 | 163 | StripedAlgorithm sa = new StripedAlgorithm(A, B, nThread); 164 | 165 | long acc = 0; 166 | for (int i = 0; i < nExperiments; i++) { 167 | long currTime = System.nanoTime(); 168 | Matrix C = sa.multiply(); 169 | acc += System.nanoTime() - currTime; 170 | } 171 | acc /= nExperiments; 172 | 173 | timeResultStriped.put(size, acc / 1_000_000); 174 | 175 | FoxAlgorithm fa = new FoxAlgorithm(A, B, nThread); 176 | 177 | acc = 0; 178 | for (int i = 0; i < nExperiments; i++) { 179 | long currTime = System.nanoTime(); 180 | Matrix C = fa.multiply(); 181 | acc += System.nanoTime() - currTime; 182 | } 183 | acc /= nExperiments; 184 | 185 | timeResultFox.put(size, acc / 1_000_000); 186 | } 187 | 188 | List keys = timeResultStriped.keySet().stream().sorted().collect(Collectors.toList()); 189 | 190 | System.out.println("**Size of matrix experiment**"); 191 | 192 | System.out.printf("%30s", "Size of matrix:"); 193 | for (int key : keys) { 194 | System.out.printf("%10d", key); 195 | System.out.print(" "); 196 | } 197 | 198 | System.out.println(); 199 | 200 | System.out.printf("%30s", "Time for Striped:"); 201 | for (int key : keys) { 202 | System.out.printf("%10d", timeResultStriped.get(key)); 203 | System.out.print(" "); 204 | } 205 | 206 | System.out.println(); 207 | 208 | System.out.printf("%30s", "Time for Fox:"); 209 | for (int key : keys) { 210 | System.out.printf("%10d", timeResultFox.get(key)); 211 | System.out.print(" "); 212 | } 213 | 214 | System.out.println("\n"); 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /Assignment2/src/com/assignment/basic/BasicAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.assignment.basic; 2 | 3 | import com.assignment.Algorithm; 4 | import com.assignment.utils.Matrix; 5 | 6 | public class BasicAlgorithm implements Algorithm { 7 | Matrix A; 8 | Matrix B; 9 | 10 | public BasicAlgorithm(Matrix A, Matrix B) { 11 | this.A = A; 12 | this.B = B; 13 | } 14 | 15 | @Override 16 | public Matrix multiply() { 17 | Matrix C = new Matrix(A.getSizeAxis0(), B.getSizeAxis1()); 18 | 19 | for (int i = 0; i < A.getSizeAxis0(); i++) { 20 | for (int j = 0; j < B.getSizeAxis1(); j++) { 21 | C.matrix[i][j] = 0; 22 | for (int k = 0; k < A.getSizeAxis1(); k++) { 23 | C.matrix[i][j] += A.matrix[i][k] * B.matrix[k][j]; 24 | } 25 | } 26 | } 27 | return C; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Assignment2/src/com/assignment/fox/FoxAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.assignment.fox; 2 | 3 | import com.assignment.Algorithm; 4 | import com.assignment.utils.Matrix; 5 | import java.util.ArrayList; 6 | import java.util.concurrent.ExecutionException; 7 | import java.util.concurrent.ExecutorService; 8 | import java.util.concurrent.Executors; 9 | import java.util.concurrent.Future; 10 | 11 | public class FoxAlgorithm implements Algorithm { 12 | Matrix A; 13 | Matrix B; 14 | private int nThread; 15 | 16 | public FoxAlgorithm(Matrix A, Matrix B, int nThread) { 17 | this.A = A; 18 | this.B = B; 19 | this.nThread = nThread; 20 | } 21 | 22 | private int findNearestDivider(int s, int p) { 23 | /* 24 | https://ru.stackoverflow.com/questions/434403/%D0%9F%D0%BE%D0%B8%D1%81%D0%BA-%D0%B1%D0%BB%D0%B8%D0%B6%D0%B0%D0%B9%D1%88%D0%B5%D0%B3%D0%BE-%D0%B4%D0%B5%D0%BB%D0%B8%D1%82%D0%B5%D0%BB%D1%8F 25 | */ 26 | int i = s; 27 | while (i > 1) { 28 | if (p % i == 0) break; 29 | if (i >= s) { 30 | i++; 31 | } else { 32 | i--; 33 | } 34 | if (i > Math.sqrt(p)) i = Math.min(s, p / s) - 1; 35 | } 36 | 37 | return i >= s ? i : i != 0 ? p / i : p; 38 | } 39 | 40 | @Override 41 | public Matrix multiply() { 42 | Matrix C = new Matrix(A.getSizeAxis0(), B.getSizeAxis1()); 43 | 44 | if (!(A.getSizeAxis0() == A.getSizeAxis1() 45 | & B.getSizeAxis0() == B.getSizeAxis1() 46 | & A.getSizeAxis0() == B.getSizeAxis0())) { 47 | try { 48 | throw new Exception("Matrix A and B have different dimensions!"); 49 | } catch (Exception e) { 50 | e.printStackTrace(); 51 | System.exit(-1); 52 | } 53 | } 54 | 55 | this.nThread = Math.min(this.nThread, A.getSizeAxis0()); 56 | this.nThread = findNearestDivider(this.nThread, A.getSizeAxis0()); 57 | int step = A.getSizeAxis0() / this.nThread; 58 | 59 | ExecutorService exec = Executors.newFixedThreadPool(this.nThread); 60 | ArrayList threads = new ArrayList<>(); 61 | 62 | int[][] matrixOfSizesI = new int[nThread][nThread]; 63 | int[][] matrixOfSizesJ = new int[nThread][nThread]; 64 | 65 | int stepI = 0; 66 | for (int i = 0; i < nThread; i++) { 67 | int stepJ = 0; 68 | for (int j = 0; j < nThread; j++) { 69 | matrixOfSizesI[i][j] = stepI; 70 | matrixOfSizesJ[i][j] = stepJ; 71 | stepJ += step; 72 | } 73 | stepI += step; 74 | } 75 | 76 | for (int l = 0; l < nThread; l++) { 77 | for (int i = 0; i < nThread; i++) { 78 | for (int j = 0; j < nThread; j++) { 79 | int stepI0 = matrixOfSizesI[i][j]; 80 | int stepJ0 = matrixOfSizesJ[i][j]; 81 | 82 | int stepI1 = matrixOfSizesI[i][(i + l) % nThread]; 83 | int stepJ1 = matrixOfSizesJ[i][(i + l) % nThread]; 84 | 85 | int stepI2 = matrixOfSizesI[(i + l) % nThread][j]; 86 | int stepJ2 = matrixOfSizesJ[(i + l) % nThread][j]; 87 | 88 | FoxAlgorithmThread t = 89 | new FoxAlgorithmThread( 90 | copyBlock(A, stepI1, stepJ1, step), 91 | copyBlock(B, stepI2, stepJ2, step), 92 | C, 93 | stepI0, 94 | stepJ0); 95 | threads.add(exec.submit(t)); 96 | } 97 | } 98 | } 99 | 100 | for (Future mapFuture : threads) { 101 | try { 102 | mapFuture.get(); 103 | } catch (InterruptedException | ExecutionException e) { 104 | e.printStackTrace(); 105 | } 106 | } 107 | 108 | exec.shutdown(); 109 | 110 | return C; 111 | } 112 | 113 | private Matrix copyBlock(Matrix matrix, int i, int j, int size) { 114 | Matrix block = new Matrix(size, size); 115 | for (int k = 0; k < size; k++) { 116 | System.arraycopy(matrix.matrix[k + i], j, block.matrix[k], 0, size); 117 | } 118 | return block; 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /Assignment2/src/com/assignment/fox/FoxAlgorithmThread.java: -------------------------------------------------------------------------------- 1 | package com.assignment.fox; 2 | 3 | import com.assignment.utils.Matrix; 4 | 5 | public class FoxAlgorithmThread extends Thread { 6 | private final Matrix A; 7 | private final Matrix B; 8 | private final Matrix C; 9 | 10 | private final int stepI; 11 | private final int stepJ; 12 | 13 | public FoxAlgorithmThread(Matrix A, Matrix B, Matrix C, int stepI, int stepJ) { 14 | this.A = A; 15 | this.B = B; 16 | this.C = C; 17 | 18 | this.stepI = stepI; 19 | this.stepJ = stepJ; 20 | } 21 | 22 | @Override 23 | public void run() { 24 | Matrix blockRes = multiplyBlock(); 25 | 26 | for (int i = 0; i < blockRes.getSizeAxis0(); i++) { 27 | for (int j = 0; j < blockRes.getSizeAxis1(); j++) { 28 | C.matrix[i + stepI][j + stepJ] += blockRes.matrix[i][j]; 29 | } 30 | } 31 | // System.out.println(Thread.currentThread().getName()); 32 | } 33 | 34 | private Matrix multiplyBlock() { 35 | Matrix blockRes = new Matrix(A.getSizeAxis1(), B.getSizeAxis0()); 36 | for (int i = 0; i < A.getSizeAxis0(); i++) { 37 | for (int j = 0; j < B.getSizeAxis1(); j++) { 38 | for (int k = 0; k < A.getSizeAxis1(); k++) { 39 | blockRes.matrix[i][j] += A.matrix[i][k] * B.matrix[k][j]; 40 | } 41 | } 42 | } 43 | return blockRes; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Assignment2/src/com/assignment/striped/StripedAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.assignment.striped; 2 | 3 | import com.assignment.*; 4 | import com.assignment.utils.Matrix; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.concurrent.*; 9 | 10 | public class StripedAlgorithm implements Algorithm { 11 | Matrix A; 12 | Matrix B; 13 | private final int nThread; 14 | 15 | public StripedAlgorithm(Matrix A, Matrix B, int nThread) { 16 | this.A = A; 17 | this.B = B; 18 | this.nThread = nThread; 19 | } 20 | 21 | @Override 22 | public Matrix multiply() { 23 | Matrix C = new Matrix(A.getSizeAxis0(), B.getSizeAxis1()); 24 | 25 | C = version1(C); 26 | // C = version2(C); 27 | // C = version3(C); 28 | // C = version4(C); 29 | 30 | return C; 31 | } 32 | 33 | public Matrix version1(Matrix C) { 34 | B.transpose(); 35 | 36 | ExecutorService executor = Executors.newFixedThreadPool(this.nThread); 37 | 38 | List>> list = new ArrayList<>(); 39 | 40 | for (int j = 0; j < B.getSizeAxis0(); j++) { 41 | for (int i = 0; i < A.getSizeAxis0(); i++) { 42 | Callable> worker = 43 | new StripedAlgorithmCallable2(A.getRow(i), i, B.getRow(j), j); 44 | Future> submit = executor.submit(worker); 45 | list.add(submit); 46 | } 47 | } 48 | 49 | for (Future> mapFuture : list) { 50 | try { 51 | Map res = mapFuture.get(); 52 | C.matrix[(int) res.get("rowIndex")][(int) res.get("columnIndex")] = 53 | (double) res.get("value"); 54 | } catch (InterruptedException | ExecutionException e) { 55 | e.printStackTrace(); 56 | } 57 | } 58 | 59 | executor.shutdown(); 60 | 61 | B.transpose(); 62 | 63 | return C; 64 | } 65 | 66 | public Matrix version2(Matrix C) { 67 | ExecutorService executor = Executors.newFixedThreadPool(this.nThread); 68 | 69 | List> list = new ArrayList<>(); 70 | 71 | for (int i = 0; i < A.getSizeAxis0(); i++) { 72 | Callable worker = new StripedAlgorithmCallable(A.getRow(i), i, B); 73 | Future submit = executor.submit(worker); 74 | list.add(submit); 75 | } 76 | 77 | for (int i = 0; i < list.size(); i++) { 78 | try { 79 | C.matrix[i] = list.get(i).get(); 80 | } catch (InterruptedException | ExecutionException e) { 81 | e.printStackTrace(); 82 | } 83 | } 84 | 85 | executor.shutdown(); 86 | 87 | return C; 88 | } 89 | 90 | public Matrix version3(Matrix C) { 91 | ArrayList threads = new ArrayList<>(); 92 | 93 | for (int i = 0; i < A.getSizeAxis0(); i++) { 94 | StripedAlgorithmThread t = new StripedAlgorithmThread(A.getRow(i), i, B); 95 | threads.add(t); 96 | threads.get(i).start(); 97 | } 98 | 99 | for (StripedAlgorithmThread t : threads) { 100 | try { 101 | t.join(); 102 | C.matrix[t.getRowIndex()] = t.getResult(); 103 | } catch (InterruptedException e) { 104 | e.printStackTrace(); 105 | } 106 | } 107 | 108 | return C; 109 | } 110 | 111 | public Matrix version4(Matrix C) { 112 | ArrayList threads = new ArrayList<>(); 113 | 114 | for (int i = 0; i < A.getSizeAxis0(); i++) { 115 | StripedAlgorithmThread2 t = new StripedAlgorithmThread2(A.getRow(i), i, B, C); 116 | threads.add(t); 117 | threads.get(i).start(); 118 | } 119 | 120 | for (StripedAlgorithmThread2 t : threads) { 121 | try { 122 | t.join(); 123 | } catch (InterruptedException e) { 124 | e.printStackTrace(); 125 | } 126 | } 127 | 128 | return C; 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /Assignment2/src/com/assignment/striped/StripedAlgorithmCallable.java: -------------------------------------------------------------------------------- 1 | package com.assignment.striped; 2 | 3 | import com.assignment.utils.Matrix; 4 | import java.util.concurrent.Callable; 5 | 6 | public class StripedAlgorithmCallable implements Callable { 7 | private final int rowIndex; 8 | private final double[] row; 9 | private Matrix B; 10 | private double[] result; 11 | 12 | public StripedAlgorithmCallable(double[] row, int rowIndex) { 13 | this.row = row; 14 | this.rowIndex = rowIndex; 15 | } 16 | 17 | public StripedAlgorithmCallable(double[] row, int rowIndex, Matrix B) { 18 | this.row = row; 19 | this.rowIndex = rowIndex; 20 | this.B = B; 21 | this.result = new double[B.getSizeAxis1()]; 22 | } 23 | 24 | @Override 25 | public double[] call() { 26 | for (int j = 0; j < B.getSizeAxis1(); j++) { 27 | // double[] column = B.getColumn(j); 28 | for (int i = 0; i < row.length; i++) { 29 | // result[j] += row[i] * column[i]; 30 | result[j] += row[i] * B.matrix[i][j]; 31 | } 32 | } 33 | 34 | // System.out.println(Thread.currentThread().getName()); 35 | return this.result; 36 | } 37 | 38 | public int getRowIndex() { 39 | return rowIndex; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Assignment2/src/com/assignment/striped/StripedAlgorithmCallable2.java: -------------------------------------------------------------------------------- 1 | package com.assignment.striped; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.concurrent.Callable; 6 | 7 | public class StripedAlgorithmCallable2 implements Callable> { 8 | private final int rowIndex; 9 | private final int columnIndex; 10 | private final double[] row; 11 | private final double[] column; 12 | 13 | public StripedAlgorithmCallable2(double[] row, int rowIndex, double[] column, int columnIndex) { 14 | this.row = row; 15 | this.rowIndex = rowIndex; 16 | this.column = column; 17 | this.columnIndex = columnIndex; 18 | } 19 | 20 | @Override 21 | public Map call() { 22 | Map result = new HashMap<>(); 23 | double value = 0; 24 | for (int i = 0; i < row.length; i++) { 25 | value += row[i] * column[i]; 26 | } 27 | 28 | result.put("value", value); 29 | result.put("rowIndex", this.rowIndex); 30 | result.put("columnIndex", this.columnIndex); 31 | return result; 32 | // System.out.println(Thread.currentThread().getName()); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Assignment2/src/com/assignment/striped/StripedAlgorithmThread.java: -------------------------------------------------------------------------------- 1 | package com.assignment.striped; 2 | 3 | import com.assignment.utils.Matrix; 4 | 5 | public class StripedAlgorithmThread extends Thread { 6 | private final int rowIndex; 7 | private final double[] row; 8 | private final double[] result; 9 | private final Matrix B; 10 | 11 | public StripedAlgorithmThread(double[] row, int rowIndex, Matrix B) { 12 | this.row = row; 13 | this.rowIndex = rowIndex; 14 | this.result = new double[B.getSizeAxis1()]; 15 | this.B = B; 16 | } 17 | 18 | @Override 19 | public void run() { 20 | for (int j = 0; j < B.getSizeAxis1(); j++) { 21 | // double[] column = B.getColumn(j); 22 | for (int i = 0; i < row.length; i++) { 23 | // result[j] += row[i] * column[i]; 24 | result[j] += row[i] * B.matrix[i][j]; 25 | } 26 | } 27 | // System.out.println(Thread.currentThread().getName()); 28 | } 29 | 30 | public int getRowIndex() { 31 | return rowIndex; 32 | } 33 | 34 | public double[] getResult() { 35 | return this.result; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Assignment2/src/com/assignment/striped/StripedAlgorithmThread2.java: -------------------------------------------------------------------------------- 1 | package com.assignment.striped; 2 | 3 | import com.assignment.utils.Matrix; 4 | 5 | public class StripedAlgorithmThread2 extends Thread { 6 | private final int rowIndex; 7 | private final double[] row; 8 | private final Matrix B; 9 | private final Matrix result; 10 | 11 | public StripedAlgorithmThread2(double[] row, int rowIndex, Matrix B, Matrix result) { 12 | this.row = row; 13 | this.rowIndex = rowIndex; 14 | this.B = B; 15 | this.result = result; 16 | } 17 | 18 | @Override 19 | public void run() { 20 | for (int j = 0; j < B.getSizeAxis1(); j++) { 21 | double temp = 0; 22 | for (int i = 0; i < row.length; i++) { 23 | temp += row[i] * B.matrix[i][j]; 24 | } 25 | result.matrix[rowIndex][j] = temp; 26 | } 27 | // System.out.println(Thread.currentThread().getName()); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Assignment2/src/com/assignment/utils/Matrix.java: -------------------------------------------------------------------------------- 1 | package com.assignment.utils; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Matrix { 6 | public double[][] matrix; 7 | private final int sizeAxis0; 8 | private final int sizeAxis1; 9 | 10 | public Matrix(int sizeAxis0, int sizeAxis1) { 11 | this.matrix = new double[sizeAxis0][sizeAxis1]; 12 | this.sizeAxis0 = sizeAxis0; 13 | this.sizeAxis1 = sizeAxis1; 14 | } 15 | 16 | public void print() { 17 | for (int i = 0; i < this.sizeAxis0; i++) { 18 | for (int j = 0; j < this.sizeAxis1; j++) { 19 | System.out.printf("%10.1f", this.matrix[i][j]); 20 | } 21 | System.out.println(); 22 | } 23 | } 24 | 25 | public void transpose() { 26 | double[][] newMatrix = new double[this.getSizeAxis1()][this.getSizeAxis0()]; 27 | for (int i = 0; i < matrix[0].length; i++) { 28 | for (int j = 0; j < matrix.length; j++) { 29 | newMatrix[i][j] = this.matrix[j][i]; 30 | } 31 | } 32 | this.matrix = newMatrix; 33 | } 34 | 35 | public double[] getRow(int index) { 36 | return this.matrix[index]; 37 | } 38 | 39 | public double[] getColumn(int index) { 40 | return Arrays.stream(matrix).mapToDouble(doubles -> doubles[index]).toArray(); 41 | } 42 | 43 | public int getSizeAxis0() { 44 | return this.sizeAxis0; 45 | } 46 | 47 | public int getSizeAxis1() { 48 | return this.sizeAxis1; 49 | } 50 | 51 | public void generateRandomMatrix() { 52 | for (int i = 0; i < this.sizeAxis0; i++) { 53 | for (int j = 0; j < this.sizeAxis1; j++) { 54 | this.matrix[i][j] = Math.random(); 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Assignment3/Assignment3.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Assignment3/src/com/assignment/task1/Bank.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task1; 2 | 3 | import java.util.concurrent.locks.ReentrantLock; 4 | 5 | public class Bank { 6 | public static final int NTEST = 10000; 7 | private final int[] accounts; 8 | // private final AtomicIntegerArray accounts; 9 | private long ntransacts = 0; 10 | // private final AtomicLong ntransacts = new AtomicLong(0); 11 | private final ReentrantLock lock = new ReentrantLock(); 12 | 13 | public Bank(int n, int initialBalance) { 14 | accounts = new int[n]; 15 | // accounts = new AtomicIntegerArray(new int[n]); 16 | int i; 17 | for (i = 0; i < accounts.length; i++) accounts[i] = initialBalance; 18 | ntransacts = 0; 19 | // for (i = 0; i < accounts.length(); i++) accounts.set(i, initialBalance); 20 | // ntransacts.set(0); 21 | } 22 | 23 | public void transfer(int from, int to, int amount) throws InterruptedException { 24 | /*accounts.addAndGet(from, -amount); 25 | accounts.addAndGet(to, amount); 26 | ntransacts.incrementAndGet(); 27 | if (ntransacts.get() % NTEST == 0) test();*/ 28 | 29 | accounts[from] -= amount; 30 | accounts[to] += amount; 31 | ntransacts++; 32 | if (ntransacts % NTEST == 0) test(); 33 | } 34 | 35 | /*public void transfer(int from, int to, int amount) throws InterruptedException { 36 | lock.lock(); 37 | accounts[from] -= amount; 38 | accounts[to] += amount; 39 | ntransacts++; 40 | if (ntransacts % NTEST == 0) test(); 41 | lock.unlock(); 42 | }*/ 43 | 44 | /*public synchronized void transfer(int from, int to, int amount) throws InterruptedException { 45 | accounts[from] -= amount; 46 | accounts[to] += amount; 47 | ntransacts++; 48 | if (ntransacts % NTEST == 0) test(); 49 | }*/ 50 | 51 | public void test() { 52 | /*AtomicInteger sum = new AtomicInteger(0); 53 | for (int i = 0; i < accounts.length(); i++) sum.addAndGet(accounts.get(i)); 54 | System.out.println("Transactions:" + ntransacts.get() + " Sum: " + sum.get());*/ 55 | 56 | int sum = 0; 57 | for (int account : accounts) sum += account; 58 | System.out.println("Transactions:" + ntransacts + " Sum: " + sum); 59 | } 60 | 61 | public int size() { 62 | return accounts.length; 63 | // return accounts.length(); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Assignment3/src/com/assignment/task1/Main.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task1; 2 | 3 | public class Main { 4 | public static final int NACCOUNTS = 10; 5 | public static final int INITIAL_BALANCE = 10000; 6 | 7 | public static void main(String[] args) { 8 | Bank b = new Bank(NACCOUNTS, INITIAL_BALANCE); 9 | int i; 10 | for (i = 0; i < NACCOUNTS; i++) { 11 | TransferThread t = new TransferThread(b, i, INITIAL_BALANCE); 12 | t.setPriority(Thread.NORM_PRIORITY + i % 2); 13 | t.start(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Assignment3/src/com/assignment/task1/TransferThread.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task1; 2 | 3 | public class TransferThread extends Thread { 4 | private final Bank bank; 5 | private final int fromAccount; 6 | private final int maxAmount; 7 | private static final int REPS = 1000; 8 | 9 | public TransferThread(Bank b, int from, int max) { 10 | bank = b; 11 | fromAccount = from; 12 | maxAmount = max; 13 | } 14 | 15 | public void run() { 16 | try { 17 | while (!interrupted()) { 18 | for (int i = 0; i < REPS; i++) { 19 | int toAccount = (int) (bank.size() * Math.random()); 20 | int amount = (int) (maxAmount * Math.random() / REPS); 21 | bank.transfer(fromAccount, toAccount, amount); 22 | Thread.sleep(1); 23 | } 24 | } 25 | } catch (InterruptedException ignored) { 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Assignment3/src/com/assignment/task2/Consumer.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task2; 2 | 3 | import java.util.Random; 4 | 5 | public class Consumer implements Runnable { 6 | private final Drop drop; 7 | 8 | public Consumer(Drop drop) { 9 | this.drop = drop; 10 | } 11 | 12 | public void run() { 13 | Random random = new Random(); 14 | for (int message = drop.take(); message != 0; message = drop.take()) { 15 | System.out.format("MESSAGE RECEIVED: %d%n", message); 16 | try { 17 | Thread.sleep(random.nextInt(5000)); 18 | } catch (InterruptedException ignored) { 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Assignment3/src/com/assignment/task2/Drop.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task2; 2 | 3 | public class Drop { 4 | // Message sent from producer 5 | // to consumer. 6 | private int message; 7 | // True if consumer should wait 8 | // for producer to send message, 9 | // false if producer should wait for 10 | // consumer to retrieve message. 11 | private boolean empty = true; 12 | 13 | public synchronized int take() { 14 | // Wait until message is 15 | // available. 16 | while (empty) { 17 | try { 18 | wait(); 19 | } catch (InterruptedException ignored) { 20 | } 21 | } 22 | // Toggle status. 23 | empty = true; 24 | // Notify producer that 25 | // status has changed. 26 | notifyAll(); 27 | return message; 28 | } 29 | 30 | public synchronized void put(int message) { 31 | // Wait until message has 32 | // been retrieved. 33 | while (!empty) { 34 | try { 35 | wait(); 36 | } catch (InterruptedException ignored) { 37 | } 38 | } 39 | // Toggle status. 40 | empty = false; 41 | // Store message. 42 | this.message = message; 43 | // Notify consumer that status 44 | // has changed. 45 | notifyAll(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Assignment3/src/com/assignment/task2/Main.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task2; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | Drop drop = new Drop(); 6 | (new Thread(new Producer(drop))).start(); 7 | (new Thread(new Consumer(drop))).start(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Assignment3/src/com/assignment/task2/Producer.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task2; 2 | 3 | import java.util.Random; 4 | 5 | public class Producer implements Runnable { 6 | private final Drop drop; 7 | 8 | public Producer(Drop drop) { 9 | this.drop = drop; 10 | } 11 | 12 | public void run() { 13 | int[] importantInfo = new int[1000]; 14 | for (int i = 0; i < importantInfo.length; i++) importantInfo[i] = i + 1; 15 | 16 | Random random = new Random(); 17 | 18 | for (int i : importantInfo) { 19 | drop.put(i); 20 | try { 21 | Thread.sleep(random.nextInt(5000)); 22 | } catch (InterruptedException ignored) { 23 | } 24 | } 25 | drop.put(0); 26 | } 27 | } 28 | 29 | /* 30 | MESSAGE RECEIVED: Mares eat oats 31 | MESSAGE RECEIVED: Does eat oats 32 | MESSAGE RECEIVED: Little lambs eat ivy 33 | MESSAGE RECEIVED: A kid will eat ivy too 34 | */ 35 | -------------------------------------------------------------------------------- /Assignment3/src/com/assignment/task3/Group.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task3; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | 7 | public class Group { 8 | private final String groupName; 9 | public HashMap> groupList = new HashMap<>(); 10 | 11 | public Group(String groupName, int sizeOfGroup) { 12 | this.groupName = groupName; 13 | generateGroupList(sizeOfGroup); 14 | } 15 | 16 | private void generateGroupList(int sizeOfGroup) { 17 | for (int i = 0; i < sizeOfGroup; i++) { 18 | this.groupList.put(i + 1, new ArrayList<>()); 19 | } 20 | } 21 | 22 | public String getGroupName() { 23 | return groupName; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Assignment3/src/com/assignment/task3/Journal.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task3; 2 | 3 | import java.util.HashMap; 4 | import java.util.stream.Collectors; 5 | 6 | public class Journal { 7 | public HashMap groups = new HashMap<>(); 8 | 9 | public Journal() { 10 | Group group1 = new Group("ІС-71", 25); 11 | Group group2 = new Group("ІС-72", 30); 12 | Group group3 = new Group("ІС-73", 26); 13 | 14 | this.groups.put(group1.getGroupName(), group1); 15 | this.groups.put(group2.getGroupName(), group2); 16 | this.groups.put(group3.getGroupName(), group3); 17 | } 18 | 19 | public void addMark(String groupName, Integer studentName, String mark) { 20 | synchronized (this.groups.get(groupName).groupList.get(studentName)) { 21 | this.groups.get(groupName).groupList.get(studentName).add(mark); 22 | } 23 | } 24 | 25 | public void show() { 26 | for (String groupName : groups.keySet().stream().sorted().collect(Collectors.toList())) { 27 | System.out.printf("Group name: %6s\n", groupName); 28 | for (Integer studentName : 29 | groups.get(groupName).groupList.keySet().stream().sorted().collect(Collectors.toList())) { 30 | System.out.printf("Student %5s %5s", studentName, "-"); 31 | for (String mark : groups.get(groupName).groupList.get(studentName)) { 32 | System.out.printf("%30s", mark); 33 | } 34 | System.out.println(); 35 | } 36 | System.out.println(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Assignment3/src/com/assignment/task3/Main.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task3; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Main { 6 | public static void main(String[] args) throws InterruptedException { 7 | Journal journal = new Journal(); 8 | int nWeeks = 3; 9 | 10 | /*Runnable r = () -> { 11 | (new Thread( new Teacher("Lecturer 1", Arrays.asList("ІС-71", "ІС-72", "ІС-73"), nWeeks, journal))).start(); 12 | (new Thread( new Teacher("Assistant 1", Collections.singletonList("ІС-71"), nWeeks, journal))).start(); 13 | (new Thread( new Teacher("Assistant 2", Collections.singletonList("ІС-72"), nWeeks, journal))).start(); 14 | (new Thread( new Teacher("Assistant 3", Collections.singletonList("ІС-73"), nWeeks, journal))).start(); 15 | };*/ 16 | 17 | Runnable r = 18 | new Runnable() { 19 | @Override 20 | public void run() { 21 | (new Thread( 22 | new Teacher( 23 | "Lecturer 1", Arrays.asList("ІС-71", "ІС-72", "ІС-73"), nWeeks, journal))) 24 | .start(); 25 | (new Thread( 26 | new Teacher( 27 | "Assistant 1", Arrays.asList("ІС-71", "ІС-72", "ІС-73"), nWeeks, journal))) 28 | .start(); 29 | (new Thread( 30 | new Teacher( 31 | "Assistant 2", Arrays.asList("ІС-71", "ІС-72", "ІС-73"), nWeeks, journal))) 32 | .start(); 33 | (new Thread( 34 | new Teacher( 35 | "Assistant 3", Arrays.asList("ІС-71", "ІС-72", "ІС-73"), nWeeks, journal))) 36 | .start(); 37 | } 38 | }; 39 | Thread t = new Thread(r); 40 | t.start(); 41 | t.join(); 42 | 43 | journal.show(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Assignment3/src/com/assignment/task3/Teacher.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task3; 2 | 3 | import java.util.List; 4 | 5 | public class Teacher implements Runnable { 6 | private final String teacherName; 7 | private final List groupNames; 8 | private final Journal journal; 9 | private final int nWeeks; 10 | 11 | public Teacher(String teacherName, List groupNames, int nWeeks, Journal journal) { 12 | this.teacherName = teacherName; 13 | this.groupNames = groupNames; 14 | this.journal = journal; 15 | this.nWeeks = nWeeks; 16 | } 17 | 18 | @Override 19 | public void run() { 20 | for (int i = 0; i < nWeeks; i++) { 21 | for (String groupName : groupNames) { 22 | for (Integer studentName : this.journal.groups.get(groupName).groupList.keySet()) { 23 | Double mark = (double) (Math.round(100 * Math.random() * 100)) / 100; 24 | journal.addMark(groupName, studentName, mark + " (" + this.teacherName + ")"); 25 | } 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Assignment4/Assignment4.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/Assignment4.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/commonWords/1.txt: -------------------------------------------------------------------------------- 1 | fameuse neutralité prussienne, ce n’est qu’un piège.1 Я верю в одного Бога и в высокую судьбу нашего милого императора. Он спасет Европу!. -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/commonWords/2.txt: -------------------------------------------------------------------------------- 1 | ерю в одного Бога и в высокую судьбу нашего милого императора. Он спасет Европу!.. — Она вдруг остановилась с улыбкой насмешки -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/keyWords/1.txt: -------------------------------------------------------------------------------- 1 | programming coding java scala python -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/keyWords/2.txt: -------------------------------------------------------------------------------- 1 | sport football tennis billiards ball jogging -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/keyWords/3.txt: -------------------------------------------------------------------------------- 1 | scala python -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/resources/commonWords/1.txt: -------------------------------------------------------------------------------- 1 | fameuse neutralité prussienne, ce n’est qu’un piège.1 Я верю в одного Бога и в высокую судьбу нашего милого императора. Он спасет Европу!. -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/resources/commonWords/2.txt: -------------------------------------------------------------------------------- 1 | ерю в одного Бога и в высокую судьбу нашего милого императора. Он спасет Европу!.. — Она вдруг остановилась с улыбкой насмешки -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/resources/keyWords/1.txt: -------------------------------------------------------------------------------- 1 | programming coding java scala python -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/resources/keyWords/2.txt: -------------------------------------------------------------------------------- 1 | sport football tennis billiards ball jogging -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/resources/keyWords/3.txt: -------------------------------------------------------------------------------- 1 | scala python -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task1/ForkJoinWordCount.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task1; 2 | 3 | import java.util.*; 4 | import java.util.concurrent.ForkJoinTask; 5 | import java.util.concurrent.RecursiveTask; 6 | 7 | public class ForkJoinWordCount extends RecursiveTask> { 8 | private final List words; 9 | private final HashMap wordCounts = new HashMap<>(); 10 | private static final int THRESHOLD = 20000; 11 | 12 | public ForkJoinWordCount(List words) { 13 | this.words = words; 14 | } 15 | 16 | @Override 17 | protected HashMap compute() { 18 | if (this.words.size() > THRESHOLD) { 19 | ForkJoinTask.invokeAll(createSubtask()).stream() 20 | .map(ForkJoinTask::join) 21 | .flatMap(map -> map.entrySet().stream()) 22 | .forEach(entry -> this.wordCounts.putIfAbsent(entry.getKey(), entry.getValue())); 23 | return this.wordCounts; 24 | } else { 25 | return processing(words); 26 | } 27 | } 28 | 29 | private Collection createSubtask() { 30 | List dividedTasks = new ArrayList<>(); 31 | dividedTasks.add(new ForkJoinWordCount(words.subList(0, words.size() / 2))); 32 | dividedTasks.add(new ForkJoinWordCount(words.subList(words.size() / 2, words.size()))); 33 | return dividedTasks; 34 | } 35 | 36 | private HashMap processing(List words) { 37 | for (String word : words) { 38 | this.wordCounts.putIfAbsent(word, word.length()); 39 | } 40 | return this.wordCounts; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task1/Main.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task1; 2 | 3 | import java.io.IOException; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.concurrent.ForkJoinPool; 7 | 8 | public class Main { 9 | public static void main(String[] args) throws IOException { 10 | List words = TextLoader.getWordsFromFile("resources/text.txt"); 11 | 12 | System.out.printf("Number of words: %d\n\n", words.size()); 13 | 14 | long currTime = System.nanoTime(); 15 | ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors()); 16 | HashMap res = pool.submit(new ForkJoinWordCount(words)).join(); 17 | long currTimeForkJoin = System.nanoTime() - currTime; 18 | 19 | System.out.printf("Execution time (ForkJoin): %d\n", currTimeForkJoin); 20 | 21 | System.out.printf("Number of uniq words: %d\n", res.keySet().size()); 22 | System.out.printf( 23 | "Mean length: %f\n", 24 | res.values().stream().mapToDouble(i -> i).sum() 25 | / res.values().stream().mapToDouble(i -> i).count()); 26 | System.out.printf( 27 | "Var length: %f\n", 28 | (res.values().stream().mapToDouble(i -> Math.pow(i, 2)).sum() 29 | / res.values().stream().mapToDouble(i -> i).count()) 30 | - Math.pow( 31 | (double) res.values().stream().mapToDouble(i -> i).sum() 32 | / res.values().stream().mapToDouble(i -> i).count(), 33 | 2)); 34 | System.out.println(); 35 | 36 | currTime = System.nanoTime(); 37 | res = SimpleWordCount.processing(words); 38 | long currTimeSimple = System.nanoTime() - currTime; 39 | 40 | System.out.printf("Execution time (Single Thread): %d\n", currTimeSimple); 41 | 42 | System.out.printf("SpeadUp = %.2f\n", (double) currTimeSimple / currTimeForkJoin); 43 | /*for (String w : res.keySet()) { 44 | System.out.println(w + " " + res.get(w)); 45 | }*/ 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task1/SimpleWordCount.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task1; 2 | 3 | import java.util.HashMap; 4 | import java.util.List; 5 | 6 | public class SimpleWordCount { 7 | public static HashMap processing(List words) { 8 | HashMap wordCounts = new HashMap<>(); 9 | 10 | for (String word : words) { 11 | wordCounts.putIfAbsent(word, word.length()); 12 | } 13 | 14 | return wordCounts; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task1/TextLoader.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task1; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Paths; 6 | import java.util.Arrays; 7 | import java.util.List; 8 | import java.util.stream.Stream; 9 | 10 | public class TextLoader { 11 | public static List getListOfWords(String text) { 12 | return Arrays.asList(text.trim().split("(\\s|\\p{Punct})+")); 13 | } 14 | 15 | public static List getLinesFromFile(String fileName) throws IOException { 16 | String[] lineBylineResult; 17 | try (Stream stream = Files.lines(Paths.get(fileName))) { 18 | lineBylineResult = stream.toArray(String[]::new); 19 | } 20 | return Arrays.asList(lineBylineResult); 21 | } 22 | 23 | public static List getWordsFromFile(String fileName) throws IOException { 24 | StringBuilder contentBuilder = new StringBuilder(); 25 | try (Stream stream = Files.lines(Paths.get(fileName))) { 26 | stream.forEach(s -> contentBuilder.append(s).append("\n")); 27 | } 28 | return TextLoader.getListOfWords(contentBuilder.toString()); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task2/Algorithm.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task2; 2 | 3 | import com.assignment.task2.utils.Matrix; 4 | 5 | public interface Algorithm { 6 | public Matrix multiply(); 7 | } 8 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task2/Main.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task2; 2 | 3 | import com.assignment.task2.basic.BasicAlgorithm; 4 | import com.assignment.task2.fox.FoxAlgorithm; 5 | import com.assignment.task2.utils.Matrix; 6 | import java.util.concurrent.ForkJoinPool; 7 | 8 | public class Main { 9 | public static void main(String[] args) { 10 | simpleRun(false); 11 | } 12 | 13 | public static void simpleRun(boolean printMatrices) { 14 | int sizeAxis0 = 2000; 15 | int sizeAxis1 = 2000; 16 | 17 | Matrix A = new Matrix(sizeAxis0, sizeAxis1); 18 | Matrix B = new Matrix(sizeAxis0, sizeAxis1); 19 | 20 | A.generateRandomMatrix(); 21 | B.generateRandomMatrix(); 22 | 23 | // A.matrix = new double[][] {{1.1, 1, 1}, {2, 2.1, 2}, {3, 3, 3}}; 24 | // B.matrix = new double[][] {{1, 1, 1}, {2, 5, 2}, {3, 3, 3}}; 25 | 26 | int nThread = Runtime.getRuntime().availableProcessors(); 27 | 28 | BasicAlgorithm ba = new BasicAlgorithm(A, B); 29 | 30 | long currTimeBasic = System.nanoTime(); 31 | Matrix C = ba.multiply(); 32 | currTimeBasic = System.nanoTime() - currTimeBasic; 33 | 34 | if (printMatrices) C.print(); 35 | 36 | System.out.println("Time for Basic Algorithm: " + currTimeBasic / 1_000_000); 37 | 38 | long currTimeFox = System.nanoTime(); 39 | ForkJoinPool forkJoinPool = new ForkJoinPool(nThread); 40 | C = forkJoinPool.invoke(new FoxAlgorithm(A, B, 6)); 41 | currTimeFox = System.nanoTime() - currTimeFox; 42 | 43 | if (printMatrices) C.print(); 44 | 45 | System.out.println("Time for Fox Algorithm: " + currTimeFox / 1_000_000); 46 | System.out.println(); 47 | System.out.println( 48 | "SpeedUp (timeBasic / timeFoxForkJoin): " + (double) currTimeBasic / currTimeFox); 49 | 50 | if (sizeAxis0 == 2000) { 51 | /* 52 | 22474 - this is average execution time for Fox algorithm (from assignment 2) 53 | */ 54 | System.out.println( 55 | "SpeedUp (timeFox / timeFoxForkJoin): " + (double) 22474 / (currTimeFox / 1_000_000)); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task2/basic/BasicAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task2.basic; 2 | 3 | import com.assignment.task2.Algorithm; 4 | import com.assignment.task2.utils.Matrix; 5 | 6 | public class BasicAlgorithm implements Algorithm { 7 | Matrix A; 8 | Matrix B; 9 | 10 | public BasicAlgorithm(Matrix A, Matrix B) { 11 | this.A = A; 12 | this.B = B; 13 | } 14 | 15 | @Override 16 | public Matrix multiply() { 17 | Matrix C = new Matrix(A.getSizeAxis0(), B.getSizeAxis1()); 18 | 19 | for (int i = 0; i < A.getSizeAxis0(); i++) { 20 | for (int j = 0; j < B.getSizeAxis1(); j++) { 21 | C.matrix[i][j] = 0; 22 | for (int k = 0; k < A.getSizeAxis1(); k++) { 23 | C.matrix[i][j] += A.matrix[i][k] * B.matrix[k][j]; 24 | } 25 | } 26 | } 27 | return C; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task2/fox/FoxAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task2.fox; 2 | 3 | import com.assignment.task2.utils.Matrix; 4 | import java.util.ArrayList; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.concurrent.*; 8 | 9 | public class FoxAlgorithm extends RecursiveTask { 10 | Matrix A; 11 | Matrix B; 12 | Matrix C; 13 | private int nBlocks; 14 | private final int step; 15 | private final int[][] matrixOfSizesI; 16 | private final int[][] matrixOfSizesJ; 17 | 18 | public FoxAlgorithm(Matrix A, Matrix B, int nBlocks) { 19 | this.A = A; 20 | this.B = B; 21 | this.C = new Matrix(A.getSizeAxis0(), B.getSizeAxis1()); 22 | this.nBlocks = nBlocks; 23 | 24 | if (!(A.getSizeAxis0() == A.getSizeAxis1() 25 | & B.getSizeAxis0() == B.getSizeAxis1() 26 | & A.getSizeAxis0() == B.getSizeAxis0())) { 27 | try { 28 | throw new Exception("Matrix A and B have different dimensions!"); 29 | } catch (Exception e) { 30 | e.printStackTrace(); 31 | System.exit(-1); 32 | } 33 | } 34 | 35 | this.nBlocks = Math.min(this.nBlocks, A.getSizeAxis0()); 36 | this.nBlocks = findNearestDivider(this.nBlocks, A.getSizeAxis0()); 37 | this.step = A.getSizeAxis0() / this.nBlocks; 38 | 39 | this.matrixOfSizesI = new int[this.nBlocks][this.nBlocks]; 40 | this.matrixOfSizesJ = new int[this.nBlocks][this.nBlocks]; 41 | 42 | preparing(); 43 | } 44 | 45 | private int findNearestDivider(int s, int p) { 46 | /* 47 | https://ru.stackoverflow.com/questions/434403/%D0%9F%D0%BE%D0%B8%D1%81%D0%BA-%D0%B1%D0%BB%D0%B8%D0%B6%D0%B0%D0%B9%D1%88%D0%B5%D0%B3%D0%BE-%D0%B4%D0%B5%D0%BB%D0%B8%D1%82%D0%B5%D0%BB%D1%8F 48 | */ 49 | int i = s; 50 | while (i > 1) { 51 | if (p % i == 0) break; 52 | if (i >= s) { 53 | i++; 54 | } else { 55 | i--; 56 | } 57 | if (i > Math.sqrt(p)) i = Math.min(s, p / s) - 1; 58 | } 59 | 60 | return i >= s ? i : i != 0 ? p / i : p; 61 | } 62 | 63 | public void preparing() { 64 | int stepI = 0; 65 | for (int i = 0; i < nBlocks; i++) { 66 | int stepJ = 0; 67 | for (int j = 0; j < nBlocks; j++) { 68 | matrixOfSizesI[i][j] = stepI; 69 | matrixOfSizesJ[i][j] = stepJ; 70 | stepJ += this.step; 71 | } 72 | stepI += this.step; 73 | } 74 | } 75 | 76 | private Matrix copyBlock(Matrix matrix, int i, int j, int size) { 77 | Matrix block = new Matrix(size, size); 78 | for (int k = 0; k < size; k++) { 79 | System.arraycopy(matrix.matrix[k + i], j, block.matrix[k], 0, size); 80 | } 81 | return block; 82 | } 83 | 84 | @Override 85 | protected Matrix compute() { 86 | List>> tasks = new ArrayList<>(); 87 | 88 | for (int l = 0; l < nBlocks; l++) { 89 | for (int i = 0; i < nBlocks; i++) { 90 | for (int j = 0; j < nBlocks; j++) { 91 | int stepI0 = matrixOfSizesI[i][j]; 92 | int stepJ0 = matrixOfSizesJ[i][j]; 93 | 94 | int stepI1 = matrixOfSizesI[i][(i + l) % nBlocks]; 95 | int stepJ1 = matrixOfSizesJ[i][(i + l) % nBlocks]; 96 | 97 | int stepI2 = matrixOfSizesI[(i + l) % nBlocks][j]; 98 | int stepJ2 = matrixOfSizesJ[(i + l) % nBlocks][j]; 99 | 100 | FoxAlgorithmForkJoin task = 101 | new FoxAlgorithmForkJoin( 102 | copyBlock(A, stepI1, stepJ1, step), 103 | copyBlock(B, stepI2, stepJ2, step), 104 | stepI0, 105 | stepJ0); 106 | 107 | tasks.add(task); 108 | task.fork(); 109 | } 110 | } 111 | } 112 | 113 | for (RecursiveTask> task : tasks) { 114 | HashMap r = task.join(); 115 | 116 | Matrix blockRes = (Matrix) r.get("blockRes"); 117 | int stepI = (int) r.get("stepI"); 118 | int stepJ = (int) r.get("stepJ"); 119 | 120 | for (int i = 0; i < blockRes.getSizeAxis0(); i++) { 121 | for (int j = 0; j < blockRes.getSizeAxis1(); j++) { 122 | C.matrix[i + stepI][j + stepJ] += blockRes.matrix[i][j]; 123 | } 124 | } 125 | } 126 | 127 | return this.C; 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task2/fox/FoxAlgorithmForkJoin.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task2.fox; 2 | 3 | import com.assignment.task2.utils.Matrix; 4 | import java.util.HashMap; 5 | import java.util.concurrent.RecursiveTask; 6 | 7 | public class FoxAlgorithmForkJoin extends RecursiveTask> { 8 | private final Matrix A; 9 | private final Matrix B; 10 | 11 | private final int stepI; 12 | private final int stepJ; 13 | 14 | public FoxAlgorithmForkJoin(Matrix A, Matrix B, int stepI, int stepJ) { 15 | this.A = A; 16 | this.B = B; 17 | 18 | this.stepI = stepI; 19 | this.stepJ = stepJ; 20 | } 21 | 22 | private Matrix multiplyBlock() { 23 | Matrix blockRes = new Matrix(A.getSizeAxis1(), B.getSizeAxis0()); 24 | for (int i = 0; i < A.getSizeAxis0(); i++) { 25 | for (int j = 0; j < B.getSizeAxis1(); j++) { 26 | for (int k = 0; k < A.getSizeAxis1(); k++) { 27 | blockRes.matrix[i][j] += A.matrix[i][k] * B.matrix[k][j]; 28 | } 29 | } 30 | } 31 | return blockRes; 32 | } 33 | 34 | @Override 35 | protected HashMap compute() { 36 | Matrix blockRes = multiplyBlock(); 37 | 38 | HashMap result = new HashMap<>(); 39 | result.put("blockRes", blockRes); 40 | result.put("stepI", stepI); 41 | result.put("stepJ", stepJ); 42 | 43 | return result; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task2/utils/Matrix.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task2.utils; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Matrix { 6 | public double[][] matrix; 7 | private final int sizeAxis0; 8 | private final int sizeAxis1; 9 | 10 | public Matrix(int sizeAxis0, int sizeAxis1) { 11 | this.matrix = new double[sizeAxis0][sizeAxis1]; 12 | this.sizeAxis0 = sizeAxis0; 13 | this.sizeAxis1 = sizeAxis1; 14 | } 15 | 16 | public void print() { 17 | for (int i = 0; i < this.sizeAxis0; i++) { 18 | for (int j = 0; j < this.sizeAxis1; j++) { 19 | System.out.printf("%10.1f", this.matrix[i][j]); 20 | } 21 | System.out.println(); 22 | } 23 | } 24 | 25 | public void transpose() { 26 | double[][] newMatrix = new double[this.getSizeAxis1()][this.getSizeAxis0()]; 27 | for (int i = 0; i < matrix[0].length; i++) { 28 | for (int j = 0; j < matrix.length; j++) { 29 | newMatrix[i][j] = this.matrix[j][i]; 30 | } 31 | } 32 | this.matrix = newMatrix; 33 | } 34 | 35 | public double[] getRow(int index) { 36 | return this.matrix[index]; 37 | } 38 | 39 | public double[] getColumn(int index) { 40 | return Arrays.stream(matrix).mapToDouble(doubles -> doubles[index]).toArray(); 41 | } 42 | 43 | public int getSizeAxis0() { 44 | return this.sizeAxis0; 45 | } 46 | 47 | public int getSizeAxis1() { 48 | return this.sizeAxis1; 49 | } 50 | 51 | public void generateRandomMatrix() { 52 | for (int i = 0; i < this.sizeAxis0; i++) { 53 | for (int j = 0; j < this.sizeAxis1; j++) { 54 | this.matrix[i][j] = Math.random(); 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task3/Document.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task3; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileReader; 6 | import java.io.IOException; 7 | import java.util.LinkedList; 8 | import java.util.List; 9 | 10 | public class Document { 11 | private final List lines; 12 | public final String documentName; 13 | 14 | Document(List lines, String documentName) { 15 | this.lines = lines; 16 | this.documentName = documentName; 17 | } 18 | 19 | List getLines() { 20 | return this.lines; 21 | } 22 | 23 | static Document fromFile(File file) throws IOException { 24 | List lines = new LinkedList<>(); 25 | try (BufferedReader reader = new BufferedReader(new FileReader(file))) { 26 | String line = reader.readLine(); 27 | while (line != null) { 28 | lines.add(line); 29 | line = reader.readLine(); 30 | } 31 | } 32 | 33 | return new Document(lines, file.getAbsolutePath()); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task3/DocumentSearchTask.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task3; 2 | 3 | import java.util.Set; 4 | import java.util.concurrent.RecursiveTask; 5 | 6 | public class DocumentSearchTask extends RecursiveTask> { 7 | private final Document document; 8 | 9 | DocumentSearchTask(Document document) { 10 | super(); 11 | this.document = document; 12 | } 13 | 14 | @Override 15 | protected Set compute() { 16 | return WordCounter.getAllWords(document); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task3/Folder.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task3; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.LinkedList; 6 | import java.util.List; 7 | import java.util.Objects; 8 | 9 | public class Folder { 10 | private final List subFolders; 11 | private final List documents; 12 | 13 | Folder(List subFolders, List documents) { 14 | this.subFolders = subFolders; 15 | this.documents = documents; 16 | } 17 | 18 | List getSubFolders() { 19 | return this.subFolders; 20 | } 21 | 22 | List getDocuments() { 23 | return this.documents; 24 | } 25 | 26 | static Folder fromDirectory(File dir) throws IOException { 27 | List documents = new LinkedList<>(); 28 | List subFolders = new LinkedList<>(); 29 | for (File entry : Objects.requireNonNull(dir.listFiles())) { 30 | if (entry.isDirectory()) { 31 | subFolders.add(Folder.fromDirectory(entry)); 32 | } else { 33 | documents.add(Document.fromFile(entry)); 34 | } 35 | } 36 | return new Folder(subFolders, documents); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task3/FolderSearchTask.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task3; 2 | 3 | import java.util.*; 4 | import java.util.concurrent.RecursiveTask; 5 | 6 | public class FolderSearchTask extends RecursiveTask> { 7 | private final Folder folder; 8 | 9 | FolderSearchTask(Folder folder) { 10 | super(); 11 | this.folder = folder; 12 | } 13 | 14 | @Override 15 | protected Set compute() { 16 | Set result; 17 | List>> forks = new LinkedList<>(); 18 | 19 | for (Folder subFolder : folder.getSubFolders()) { 20 | FolderSearchTask task = new FolderSearchTask(subFolder); 21 | forks.add(task); 22 | task.fork(); 23 | } 24 | for (Document document : folder.getDocuments()) { 25 | DocumentSearchTask task = new DocumentSearchTask(document); 26 | forks.add(task); 27 | task.fork(); 28 | } 29 | 30 | if (forks.size() == 0) return new HashSet<>(); 31 | 32 | result = forks.get(0).join(); 33 | forks.remove(0); 34 | for (RecursiveTask> task : forks) { 35 | result.retainAll(task.join()); 36 | } 37 | 38 | return result; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task3/Main.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task3; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | public class Main { 7 | public static void main(String[] args) throws IOException { 8 | String folderName = "resources/commonWords"; 9 | 10 | WordCounter wordCounter = new WordCounter(); 11 | Folder folder = Folder.fromDirectory(new File(folderName)); 12 | 13 | System.out.println(wordCounter.getCommonWordsInParallel(folder)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task3/WordCounter.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task3; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | import java.util.concurrent.ForkJoinPool; 7 | 8 | public class WordCounter { 9 | 10 | public static String[] wordsIn(String line) { 11 | return line.trim().split("(\\s|\\p{Punct})+"); 12 | } 13 | 14 | public static Set getAllWords(Document document) { 15 | Set allWords = new HashSet<>(); 16 | for (String line : document.getLines()) { 17 | allWords.addAll(Arrays.asList(wordsIn(line))); 18 | } 19 | return allWords; 20 | } 21 | 22 | private final ForkJoinPool forkJoinPool = 23 | new ForkJoinPool(Runtime.getRuntime().availableProcessors()); 24 | 25 | public Set getCommonWordsInParallel(Folder folder) { 26 | return forkJoinPool.invoke(new FolderSearchTask(folder)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task4/Document.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task4; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileReader; 6 | import java.io.IOException; 7 | import java.util.LinkedList; 8 | import java.util.List; 9 | 10 | public class Document { 11 | private final List lines; 12 | public final String documentName; 13 | 14 | Document(List lines, String documentName) { 15 | this.lines = lines; 16 | this.documentName = documentName; 17 | } 18 | 19 | List getLines() { 20 | return this.lines; 21 | } 22 | 23 | static Document fromFile(File file) throws IOException { 24 | List lines = new LinkedList<>(); 25 | try (BufferedReader reader = new BufferedReader(new FileReader(file))) { 26 | String line = reader.readLine(); 27 | while (line != null) { 28 | lines.add(line); 29 | line = reader.readLine(); 30 | } 31 | } 32 | 33 | return new Document(lines, file.getAbsolutePath()); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task4/DocumentSearchTask.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task4; 2 | 3 | import java.util.Collections; 4 | import java.util.List; 5 | import java.util.concurrent.RecursiveTask; 6 | 7 | public class DocumentSearchTask extends RecursiveTask> { 8 | private final Document document; 9 | private final List searchedWords; 10 | 11 | DocumentSearchTask(Document document, List searchedWords) { 12 | super(); 13 | this.document = document; 14 | this.searchedWords = searchedWords; 15 | } 16 | 17 | @Override 18 | protected List compute() { 19 | return WordCounter.occurrencesCount(document, searchedWords) == 0 20 | ? null 21 | : Collections.singletonList(document.documentName); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task4/Folder.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task4; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.LinkedList; 6 | import java.util.List; 7 | import java.util.Objects; 8 | 9 | public class Folder { 10 | private final List subFolders; 11 | private final List documents; 12 | 13 | Folder(List subFolders, List documents) { 14 | this.subFolders = subFolders; 15 | this.documents = documents; 16 | } 17 | 18 | List getSubFolders() { 19 | return this.subFolders; 20 | } 21 | 22 | List getDocuments() { 23 | return this.documents; 24 | } 25 | 26 | public static Folder fromDirectory(File dir) throws IOException { 27 | List documents = new LinkedList<>(); 28 | List subFolders = new LinkedList<>(); 29 | for (File entry : Objects.requireNonNull(dir.listFiles())) { 30 | if (entry.isDirectory()) { 31 | subFolders.add(Folder.fromDirectory(entry)); 32 | } else { 33 | documents.add(Document.fromFile(entry)); 34 | } 35 | } 36 | return new Folder(subFolders, documents); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task4/FolderSearchTask.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task4; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | import java.util.concurrent.RecursiveTask; 7 | 8 | public class FolderSearchTask extends RecursiveTask> { 9 | private final Folder folder; 10 | private final List searchedWords; 11 | 12 | FolderSearchTask(Folder folder, List searchedWords) { 13 | super(); 14 | this.folder = folder; 15 | this.searchedWords = searchedWords; 16 | } 17 | 18 | @Override 19 | protected List compute() { 20 | List>> forks = new LinkedList<>(); 21 | 22 | for (Folder subFolder : folder.getSubFolders()) { 23 | FolderSearchTask task = new FolderSearchTask(subFolder, searchedWords); 24 | forks.add(task); 25 | task.fork(); 26 | } 27 | for (Document document : folder.getDocuments()) { 28 | DocumentSearchTask task = new DocumentSearchTask(document, searchedWords); 29 | forks.add(task); 30 | task.fork(); 31 | } 32 | 33 | List result = new ArrayList<>(); 34 | for (RecursiveTask> task : forks) { 35 | List taskResult = task.join(); 36 | if (taskResult == null) { 37 | continue; 38 | } 39 | result.addAll(taskResult); 40 | } 41 | return result; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task4/Main.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task4; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.Arrays; 6 | import java.util.List; 7 | 8 | public class Main { 9 | public static void main(String[] args) throws IOException { 10 | String folderName = "resources"; 11 | List keyWords = Arrays.asList("java", "scala"); 12 | 13 | WordCounter wordCounter = new WordCounter(); 14 | Folder folder = Folder.fromDirectory(new File(folderName)); 15 | 16 | for (String documentName : wordCounter.countOccurrencesInParallel(folder, keyWords)) 17 | System.out.println(documentName); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Assignment4/out/production/Assignment4/src/com/assignment/task4/WordCounter.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task4; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.ForkJoinPool; 5 | 6 | public class WordCounter { 7 | 8 | public static String[] wordsIn(String line) { 9 | return line.trim().split("(\\s|\\p{Punct})+"); 10 | } 11 | 12 | public static Long occurrencesCount(Document document, List searchedWords) { 13 | long count = 0; 14 | for (String line : document.getLines()) { 15 | for (String word : wordsIn(line)) { 16 | if (searchedWords.contains(word)) { 17 | count = count + 1; 18 | } 19 | } 20 | } 21 | return count; 22 | } 23 | 24 | private final ForkJoinPool forkJoinPool = 25 | new ForkJoinPool(Runtime.getRuntime().availableProcessors()); 26 | 27 | public List countOccurrencesInParallel(Folder folder, List searchedWords) { 28 | return forkJoinPool.invoke(new FolderSearchTask(folder, searchedWords)); 29 | } 30 | 31 | public Long countOccurrencesOnSingleThread(Folder folder, List searchedWords) { 32 | long count = 0; 33 | for (Folder subFolder : folder.getSubFolders()) { 34 | count = count + countOccurrencesOnSingleThread(subFolder, searchedWords); 35 | } 36 | for (Document document : folder.getDocuments()) { 37 | count = count + occurrencesCount(document, searchedWords); 38 | } 39 | return count; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Assignment4/resources/commonWords/1.txt: -------------------------------------------------------------------------------- 1 | fameuse neutralité prussienne, ce n’est qu’un piège.1 Я верю в одного Бога и в высокую судьбу нашего милого императора. Он спасет Европу!. -------------------------------------------------------------------------------- /Assignment4/resources/commonWords/2.txt: -------------------------------------------------------------------------------- 1 | ерю в одного Бога и в высокую судьбу нашего милого императора. Он спасет Европу!.. — Она вдруг остановилась с улыбкой насмешки -------------------------------------------------------------------------------- /Assignment4/resources/keyWords/1.txt: -------------------------------------------------------------------------------- 1 | programming coding java scala python -------------------------------------------------------------------------------- /Assignment4/resources/keyWords/2.txt: -------------------------------------------------------------------------------- 1 | sport football tennis billiards ball jogging -------------------------------------------------------------------------------- /Assignment4/resources/keyWords/3.txt: -------------------------------------------------------------------------------- 1 | scala python -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task1/ForkJoinWordCount.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task1; 2 | 3 | import java.util.*; 4 | import java.util.concurrent.ForkJoinTask; 5 | import java.util.concurrent.RecursiveTask; 6 | 7 | public class ForkJoinWordCount extends RecursiveTask> { 8 | private final List words; 9 | private final HashMap wordCounts = new HashMap<>(); 10 | private static final int THRESHOLD = 20000; 11 | 12 | public ForkJoinWordCount(List words) { 13 | this.words = words; 14 | } 15 | 16 | @Override 17 | protected HashMap compute() { 18 | if (this.words.size() > THRESHOLD) { 19 | ForkJoinTask.invokeAll(createSubtask()).stream() 20 | .map(ForkJoinTask::join) 21 | .flatMap(map -> map.entrySet().stream()) 22 | .forEach(entry -> this.wordCounts.putIfAbsent(entry.getKey(), entry.getValue())); 23 | return this.wordCounts; 24 | } else { 25 | return processing(words); 26 | } 27 | } 28 | 29 | private Collection createSubtask() { 30 | List dividedTasks = new ArrayList<>(); 31 | dividedTasks.add(new ForkJoinWordCount(words.subList(0, words.size() / 2))); 32 | dividedTasks.add(new ForkJoinWordCount(words.subList(words.size() / 2, words.size()))); 33 | return dividedTasks; 34 | } 35 | 36 | private HashMap processing(List words) { 37 | for (String word : words) { 38 | this.wordCounts.putIfAbsent(word, word.length()); 39 | } 40 | return this.wordCounts; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task1/Main.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task1; 2 | 3 | import java.io.IOException; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.concurrent.ForkJoinPool; 7 | 8 | public class Main { 9 | public static void main(String[] args) throws IOException { 10 | List words = TextLoader.getWordsFromFile("resources/text.txt"); 11 | 12 | System.out.printf("Number of words: %d\n\n", words.size()); 13 | 14 | long currTime = System.nanoTime(); 15 | ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors()); 16 | HashMap res = pool.submit(new ForkJoinWordCount(words)).join(); 17 | long currTimeForkJoin = System.nanoTime() - currTime; 18 | 19 | System.out.printf("Execution time (ForkJoin): %d\n", currTimeForkJoin); 20 | 21 | System.out.printf("Number of uniq words: %d\n", res.keySet().size()); 22 | System.out.printf( 23 | "Mean length: %f\n", 24 | res.values().stream().mapToDouble(i -> i).sum() 25 | / res.values().stream().mapToDouble(i -> i).count()); 26 | System.out.printf( 27 | "Var length: %f\n", 28 | (res.values().stream().mapToDouble(i -> Math.pow(i, 2)).sum() 29 | / res.values().stream().mapToDouble(i -> i).count()) 30 | - Math.pow( 31 | (double) res.values().stream().mapToDouble(i -> i).sum() 32 | / res.values().stream().mapToDouble(i -> i).count(), 33 | 2)); 34 | System.out.println(); 35 | 36 | currTime = System.nanoTime(); 37 | res = SimpleWordCount.processing(words); 38 | long currTimeSimple = System.nanoTime() - currTime; 39 | 40 | System.out.printf("Execution time (Single Thread): %d\n", currTimeSimple); 41 | 42 | System.out.printf("SpeadUp = %.2f\n", (double) currTimeSimple / currTimeForkJoin); 43 | /*for (String w : res.keySet()) { 44 | System.out.println(w + " " + res.get(w)); 45 | }*/ 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task1/SimpleWordCount.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task1; 2 | 3 | import java.util.HashMap; 4 | import java.util.List; 5 | 6 | public class SimpleWordCount { 7 | public static HashMap processing(List words) { 8 | HashMap wordCounts = new HashMap<>(); 9 | 10 | for (String word : words) { 11 | wordCounts.putIfAbsent(word, word.length()); 12 | } 13 | 14 | return wordCounts; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task1/TextLoader.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task1; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Paths; 6 | import java.util.Arrays; 7 | import java.util.List; 8 | import java.util.stream.Stream; 9 | 10 | public class TextLoader { 11 | public static List getListOfWords(String text) { 12 | return Arrays.asList(text.trim().split("(\\s|\\p{Punct})+")); 13 | } 14 | 15 | public static List getLinesFromFile(String fileName) throws IOException { 16 | String[] lineBylineResult; 17 | try (Stream stream = Files.lines(Paths.get(fileName))) { 18 | lineBylineResult = stream.toArray(String[]::new); 19 | } 20 | return Arrays.asList(lineBylineResult); 21 | } 22 | 23 | public static List getWordsFromFile(String fileName) throws IOException { 24 | StringBuilder contentBuilder = new StringBuilder(); 25 | try (Stream stream = Files.lines(Paths.get(fileName))) { 26 | stream.forEach(s -> contentBuilder.append(s).append("\n")); 27 | } 28 | return TextLoader.getListOfWords(contentBuilder.toString()); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task2/Algorithm.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task2; 2 | 3 | import com.assignment.task2.utils.Matrix; 4 | 5 | public interface Algorithm { 6 | public Matrix multiply(); 7 | } 8 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task2/Main.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task2; 2 | 3 | import com.assignment.task2.basic.BasicAlgorithm; 4 | import com.assignment.task2.fox.FoxAlgorithm; 5 | import com.assignment.task2.utils.Matrix; 6 | import java.util.concurrent.ForkJoinPool; 7 | 8 | public class Main { 9 | public static void main(String[] args) { 10 | simpleRun(false); 11 | } 12 | 13 | public static void simpleRun(boolean printMatrices) { 14 | int sizeAxis0 = 2000; 15 | int sizeAxis1 = 2000; 16 | 17 | Matrix A = new Matrix(sizeAxis0, sizeAxis1); 18 | Matrix B = new Matrix(sizeAxis0, sizeAxis1); 19 | 20 | A.generateRandomMatrix(); 21 | B.generateRandomMatrix(); 22 | 23 | // A.matrix = new double[][] {{1.1, 1, 1}, {2, 2.1, 2}, {3, 3, 3}}; 24 | // B.matrix = new double[][] {{1, 1, 1}, {2, 5, 2}, {3, 3, 3}}; 25 | 26 | int nThread = Runtime.getRuntime().availableProcessors(); 27 | 28 | BasicAlgorithm ba = new BasicAlgorithm(A, B); 29 | 30 | long currTimeBasic = System.nanoTime(); 31 | Matrix C = ba.multiply(); 32 | currTimeBasic = System.nanoTime() - currTimeBasic; 33 | 34 | if (printMatrices) C.print(); 35 | 36 | System.out.println("Time for Basic Algorithm: " + currTimeBasic / 1_000_000); 37 | 38 | long currTimeFox = System.nanoTime(); 39 | ForkJoinPool forkJoinPool = new ForkJoinPool(nThread); 40 | C = forkJoinPool.invoke(new FoxAlgorithm(A, B, 6)); 41 | currTimeFox = System.nanoTime() - currTimeFox; 42 | 43 | if (printMatrices) C.print(); 44 | 45 | System.out.println("Time for Fox Algorithm: " + currTimeFox / 1_000_000); 46 | System.out.println(); 47 | System.out.println( 48 | "SpeedUp (timeBasic / timeFoxForkJoin): " + (double) currTimeBasic / currTimeFox); 49 | 50 | if (sizeAxis0 == 2000) { 51 | /* 52 | 22474 - this is average execution time for Fox algorithm (from assignment 2) 53 | */ 54 | System.out.println( 55 | "SpeedUp (timeFox / timeFoxForkJoin): " + (double) 22474 / (currTimeFox / 1_000_000)); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task2/basic/BasicAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task2.basic; 2 | 3 | import com.assignment.task2.Algorithm; 4 | import com.assignment.task2.utils.Matrix; 5 | 6 | public class BasicAlgorithm implements Algorithm { 7 | Matrix A; 8 | Matrix B; 9 | 10 | public BasicAlgorithm(Matrix A, Matrix B) { 11 | this.A = A; 12 | this.B = B; 13 | } 14 | 15 | @Override 16 | public Matrix multiply() { 17 | Matrix C = new Matrix(A.getSizeAxis0(), B.getSizeAxis1()); 18 | 19 | for (int i = 0; i < A.getSizeAxis0(); i++) { 20 | for (int j = 0; j < B.getSizeAxis1(); j++) { 21 | C.matrix[i][j] = 0; 22 | for (int k = 0; k < A.getSizeAxis1(); k++) { 23 | C.matrix[i][j] += A.matrix[i][k] * B.matrix[k][j]; 24 | } 25 | } 26 | } 27 | return C; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task2/fox/FoxAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task2.fox; 2 | 3 | import com.assignment.task2.utils.Matrix; 4 | import java.util.ArrayList; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.concurrent.*; 8 | 9 | public class FoxAlgorithm extends RecursiveTask { 10 | Matrix A; 11 | Matrix B; 12 | Matrix C; 13 | private int nBlocks; 14 | private final int step; 15 | private final int[][] matrixOfSizesI; 16 | private final int[][] matrixOfSizesJ; 17 | 18 | public FoxAlgorithm(Matrix A, Matrix B, int nBlocks) { 19 | this.A = A; 20 | this.B = B; 21 | this.C = new Matrix(A.getSizeAxis0(), B.getSizeAxis1()); 22 | this.nBlocks = nBlocks; 23 | 24 | if (!(A.getSizeAxis0() == A.getSizeAxis1() 25 | & B.getSizeAxis0() == B.getSizeAxis1() 26 | & A.getSizeAxis0() == B.getSizeAxis0())) { 27 | try { 28 | throw new Exception("Matrix A and B have different dimensions!"); 29 | } catch (Exception e) { 30 | e.printStackTrace(); 31 | System.exit(-1); 32 | } 33 | } 34 | 35 | this.nBlocks = Math.min(this.nBlocks, A.getSizeAxis0()); 36 | this.nBlocks = findNearestDivider(this.nBlocks, A.getSizeAxis0()); 37 | this.step = A.getSizeAxis0() / this.nBlocks; 38 | 39 | this.matrixOfSizesI = new int[this.nBlocks][this.nBlocks]; 40 | this.matrixOfSizesJ = new int[this.nBlocks][this.nBlocks]; 41 | 42 | preparing(); 43 | } 44 | 45 | private int findNearestDivider(int s, int p) { 46 | /* 47 | https://ru.stackoverflow.com/questions/434403/%D0%9F%D0%BE%D0%B8%D1%81%D0%BA-%D0%B1%D0%BB%D0%B8%D0%B6%D0%B0%D0%B9%D1%88%D0%B5%D0%B3%D0%BE-%D0%B4%D0%B5%D0%BB%D0%B8%D1%82%D0%B5%D0%BB%D1%8F 48 | */ 49 | int i = s; 50 | while (i > 1) { 51 | if (p % i == 0) break; 52 | if (i >= s) { 53 | i++; 54 | } else { 55 | i--; 56 | } 57 | if (i > Math.sqrt(p)) i = Math.min(s, p / s) - 1; 58 | } 59 | 60 | return i >= s ? i : i != 0 ? p / i : p; 61 | } 62 | 63 | public void preparing() { 64 | int stepI = 0; 65 | for (int i = 0; i < nBlocks; i++) { 66 | int stepJ = 0; 67 | for (int j = 0; j < nBlocks; j++) { 68 | matrixOfSizesI[i][j] = stepI; 69 | matrixOfSizesJ[i][j] = stepJ; 70 | stepJ += this.step; 71 | } 72 | stepI += this.step; 73 | } 74 | } 75 | 76 | private Matrix copyBlock(Matrix matrix, int i, int j, int size) { 77 | Matrix block = new Matrix(size, size); 78 | for (int k = 0; k < size; k++) { 79 | System.arraycopy(matrix.matrix[k + i], j, block.matrix[k], 0, size); 80 | } 81 | return block; 82 | } 83 | 84 | @Override 85 | protected Matrix compute() { 86 | List>> tasks = new ArrayList<>(); 87 | 88 | for (int l = 0; l < nBlocks; l++) { 89 | for (int i = 0; i < nBlocks; i++) { 90 | for (int j = 0; j < nBlocks; j++) { 91 | int stepI0 = matrixOfSizesI[i][j]; 92 | int stepJ0 = matrixOfSizesJ[i][j]; 93 | 94 | int stepI1 = matrixOfSizesI[i][(i + l) % nBlocks]; 95 | int stepJ1 = matrixOfSizesJ[i][(i + l) % nBlocks]; 96 | 97 | int stepI2 = matrixOfSizesI[(i + l) % nBlocks][j]; 98 | int stepJ2 = matrixOfSizesJ[(i + l) % nBlocks][j]; 99 | 100 | FoxAlgorithmForkJoin task = 101 | new FoxAlgorithmForkJoin( 102 | copyBlock(A, stepI1, stepJ1, step), 103 | copyBlock(B, stepI2, stepJ2, step), 104 | stepI0, 105 | stepJ0); 106 | 107 | tasks.add(task); 108 | task.fork(); 109 | } 110 | } 111 | } 112 | 113 | for (RecursiveTask> task : tasks) { 114 | HashMap r = task.join(); 115 | 116 | Matrix blockRes = (Matrix) r.get("blockRes"); 117 | int stepI = (int) r.get("stepI"); 118 | int stepJ = (int) r.get("stepJ"); 119 | 120 | for (int i = 0; i < blockRes.getSizeAxis0(); i++) { 121 | for (int j = 0; j < blockRes.getSizeAxis1(); j++) { 122 | C.matrix[i + stepI][j + stepJ] += blockRes.matrix[i][j]; 123 | } 124 | } 125 | } 126 | 127 | return this.C; 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task2/fox/FoxAlgorithmForkJoin.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task2.fox; 2 | 3 | import com.assignment.task2.utils.Matrix; 4 | import java.util.HashMap; 5 | import java.util.concurrent.RecursiveTask; 6 | 7 | public class FoxAlgorithmForkJoin extends RecursiveTask> { 8 | private final Matrix A; 9 | private final Matrix B; 10 | 11 | private final int stepI; 12 | private final int stepJ; 13 | 14 | public FoxAlgorithmForkJoin(Matrix A, Matrix B, int stepI, int stepJ) { 15 | this.A = A; 16 | this.B = B; 17 | 18 | this.stepI = stepI; 19 | this.stepJ = stepJ; 20 | } 21 | 22 | private Matrix multiplyBlock() { 23 | Matrix blockRes = new Matrix(A.getSizeAxis1(), B.getSizeAxis0()); 24 | for (int i = 0; i < A.getSizeAxis0(); i++) { 25 | for (int j = 0; j < B.getSizeAxis1(); j++) { 26 | for (int k = 0; k < A.getSizeAxis1(); k++) { 27 | blockRes.matrix[i][j] += A.matrix[i][k] * B.matrix[k][j]; 28 | } 29 | } 30 | } 31 | return blockRes; 32 | } 33 | 34 | @Override 35 | protected HashMap compute() { 36 | Matrix blockRes = multiplyBlock(); 37 | 38 | HashMap result = new HashMap<>(); 39 | result.put("blockRes", blockRes); 40 | result.put("stepI", stepI); 41 | result.put("stepJ", stepJ); 42 | 43 | return result; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task2/utils/Matrix.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task2.utils; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Matrix { 6 | public double[][] matrix; 7 | private final int sizeAxis0; 8 | private final int sizeAxis1; 9 | 10 | public Matrix(int sizeAxis0, int sizeAxis1) { 11 | this.matrix = new double[sizeAxis0][sizeAxis1]; 12 | this.sizeAxis0 = sizeAxis0; 13 | this.sizeAxis1 = sizeAxis1; 14 | } 15 | 16 | public void print() { 17 | for (int i = 0; i < this.sizeAxis0; i++) { 18 | for (int j = 0; j < this.sizeAxis1; j++) { 19 | System.out.printf("%10.1f", this.matrix[i][j]); 20 | } 21 | System.out.println(); 22 | } 23 | } 24 | 25 | public void transpose() { 26 | double[][] newMatrix = new double[this.getSizeAxis1()][this.getSizeAxis0()]; 27 | for (int i = 0; i < matrix[0].length; i++) { 28 | for (int j = 0; j < matrix.length; j++) { 29 | newMatrix[i][j] = this.matrix[j][i]; 30 | } 31 | } 32 | this.matrix = newMatrix; 33 | } 34 | 35 | public double[] getRow(int index) { 36 | return this.matrix[index]; 37 | } 38 | 39 | public double[] getColumn(int index) { 40 | return Arrays.stream(matrix).mapToDouble(doubles -> doubles[index]).toArray(); 41 | } 42 | 43 | public int getSizeAxis0() { 44 | return this.sizeAxis0; 45 | } 46 | 47 | public int getSizeAxis1() { 48 | return this.sizeAxis1; 49 | } 50 | 51 | public void generateRandomMatrix() { 52 | for (int i = 0; i < this.sizeAxis0; i++) { 53 | for (int j = 0; j < this.sizeAxis1; j++) { 54 | this.matrix[i][j] = Math.random(); 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task3/Document.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task3; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileReader; 6 | import java.io.IOException; 7 | import java.util.LinkedList; 8 | import java.util.List; 9 | 10 | public class Document { 11 | private final List lines; 12 | public final String documentName; 13 | 14 | Document(List lines, String documentName) { 15 | this.lines = lines; 16 | this.documentName = documentName; 17 | } 18 | 19 | List getLines() { 20 | return this.lines; 21 | } 22 | 23 | static Document fromFile(File file) throws IOException { 24 | List lines = new LinkedList<>(); 25 | try (BufferedReader reader = new BufferedReader(new FileReader(file))) { 26 | String line = reader.readLine(); 27 | while (line != null) { 28 | lines.add(line); 29 | line = reader.readLine(); 30 | } 31 | } 32 | 33 | return new Document(lines, file.getAbsolutePath()); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task3/DocumentSearchTask.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task3; 2 | 3 | import java.util.Set; 4 | import java.util.concurrent.RecursiveTask; 5 | 6 | public class DocumentSearchTask extends RecursiveTask> { 7 | private final Document document; 8 | 9 | DocumentSearchTask(Document document) { 10 | super(); 11 | this.document = document; 12 | } 13 | 14 | @Override 15 | protected Set compute() { 16 | return WordCounter.getAllWords(document); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task3/Folder.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task3; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.LinkedList; 6 | import java.util.List; 7 | import java.util.Objects; 8 | 9 | public class Folder { 10 | private final List subFolders; 11 | private final List documents; 12 | 13 | Folder(List subFolders, List documents) { 14 | this.subFolders = subFolders; 15 | this.documents = documents; 16 | } 17 | 18 | List getSubFolders() { 19 | return this.subFolders; 20 | } 21 | 22 | List getDocuments() { 23 | return this.documents; 24 | } 25 | 26 | static Folder fromDirectory(File dir) throws IOException { 27 | List documents = new LinkedList<>(); 28 | List subFolders = new LinkedList<>(); 29 | for (File entry : Objects.requireNonNull(dir.listFiles())) { 30 | if (entry.isDirectory()) { 31 | subFolders.add(Folder.fromDirectory(entry)); 32 | } else { 33 | documents.add(Document.fromFile(entry)); 34 | } 35 | } 36 | return new Folder(subFolders, documents); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task3/FolderSearchTask.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task3; 2 | 3 | import java.util.*; 4 | import java.util.concurrent.RecursiveTask; 5 | 6 | public class FolderSearchTask extends RecursiveTask> { 7 | private final Folder folder; 8 | 9 | FolderSearchTask(Folder folder) { 10 | super(); 11 | this.folder = folder; 12 | } 13 | 14 | @Override 15 | protected Set compute() { 16 | Set result; 17 | List>> forks = new LinkedList<>(); 18 | 19 | for (Folder subFolder : folder.getSubFolders()) { 20 | FolderSearchTask task = new FolderSearchTask(subFolder); 21 | forks.add(task); 22 | task.fork(); 23 | } 24 | for (Document document : folder.getDocuments()) { 25 | DocumentSearchTask task = new DocumentSearchTask(document); 26 | forks.add(task); 27 | task.fork(); 28 | } 29 | 30 | if (forks.size() == 0) return new HashSet<>(); 31 | 32 | result = forks.get(0).join(); 33 | forks.remove(0); 34 | for (RecursiveTask> task : forks) { 35 | result.retainAll(task.join()); 36 | } 37 | 38 | return result; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task3/Main.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task3; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | public class Main { 7 | public static void main(String[] args) throws IOException { 8 | String folderName = "resources/commonWords"; 9 | 10 | WordCounter wordCounter = new WordCounter(); 11 | Folder folder = Folder.fromDirectory(new File(folderName)); 12 | 13 | System.out.println(wordCounter.getCommonWordsInParallel(folder)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task3/WordCounter.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task3; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | import java.util.concurrent.ForkJoinPool; 7 | 8 | public class WordCounter { 9 | 10 | public static String[] wordsIn(String line) { 11 | return line.trim().split("(\\s|\\p{Punct})+"); 12 | } 13 | 14 | public static Set getAllWords(Document document) { 15 | Set allWords = new HashSet<>(); 16 | for (String line : document.getLines()) { 17 | allWords.addAll(Arrays.asList(wordsIn(line))); 18 | } 19 | return allWords; 20 | } 21 | 22 | private final ForkJoinPool forkJoinPool = 23 | new ForkJoinPool(Runtime.getRuntime().availableProcessors()); 24 | 25 | public Set getCommonWordsInParallel(Folder folder) { 26 | return forkJoinPool.invoke(new FolderSearchTask(folder)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task4/Document.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task4; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileReader; 6 | import java.io.IOException; 7 | import java.util.LinkedList; 8 | import java.util.List; 9 | 10 | public class Document { 11 | private final List lines; 12 | public final String documentName; 13 | 14 | Document(List lines, String documentName) { 15 | this.lines = lines; 16 | this.documentName = documentName; 17 | } 18 | 19 | List getLines() { 20 | return this.lines; 21 | } 22 | 23 | static Document fromFile(File file) throws IOException { 24 | List lines = new LinkedList<>(); 25 | try (BufferedReader reader = new BufferedReader(new FileReader(file))) { 26 | String line = reader.readLine(); 27 | while (line != null) { 28 | lines.add(line); 29 | line = reader.readLine(); 30 | } 31 | } 32 | 33 | return new Document(lines, file.getAbsolutePath()); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task4/DocumentSearchTask.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task4; 2 | 3 | import java.util.Collections; 4 | import java.util.List; 5 | import java.util.concurrent.RecursiveTask; 6 | 7 | public class DocumentSearchTask extends RecursiveTask> { 8 | private final Document document; 9 | private final List searchedWords; 10 | 11 | DocumentSearchTask(Document document, List searchedWords) { 12 | super(); 13 | this.document = document; 14 | this.searchedWords = searchedWords; 15 | } 16 | 17 | @Override 18 | protected List compute() { 19 | return WordCounter.occurrencesCount(document, searchedWords) == 0 20 | ? null 21 | : Collections.singletonList(document.documentName); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task4/Folder.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task4; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.LinkedList; 6 | import java.util.List; 7 | import java.util.Objects; 8 | 9 | public class Folder { 10 | private final List subFolders; 11 | private final List documents; 12 | 13 | Folder(List subFolders, List documents) { 14 | this.subFolders = subFolders; 15 | this.documents = documents; 16 | } 17 | 18 | List getSubFolders() { 19 | return this.subFolders; 20 | } 21 | 22 | List getDocuments() { 23 | return this.documents; 24 | } 25 | 26 | public static Folder fromDirectory(File dir) throws IOException { 27 | List documents = new LinkedList<>(); 28 | List subFolders = new LinkedList<>(); 29 | for (File entry : Objects.requireNonNull(dir.listFiles())) { 30 | if (entry.isDirectory()) { 31 | subFolders.add(Folder.fromDirectory(entry)); 32 | } else { 33 | documents.add(Document.fromFile(entry)); 34 | } 35 | } 36 | return new Folder(subFolders, documents); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task4/FolderSearchTask.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task4; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | import java.util.concurrent.RecursiveTask; 7 | 8 | public class FolderSearchTask extends RecursiveTask> { 9 | private final Folder folder; 10 | private final List searchedWords; 11 | 12 | FolderSearchTask(Folder folder, List searchedWords) { 13 | super(); 14 | this.folder = folder; 15 | this.searchedWords = searchedWords; 16 | } 17 | 18 | @Override 19 | protected List compute() { 20 | List>> forks = new LinkedList<>(); 21 | 22 | for (Folder subFolder : folder.getSubFolders()) { 23 | FolderSearchTask task = new FolderSearchTask(subFolder, searchedWords); 24 | forks.add(task); 25 | task.fork(); 26 | } 27 | for (Document document : folder.getDocuments()) { 28 | DocumentSearchTask task = new DocumentSearchTask(document, searchedWords); 29 | forks.add(task); 30 | task.fork(); 31 | } 32 | 33 | List result = new ArrayList<>(); 34 | for (RecursiveTask> task : forks) { 35 | List taskResult = task.join(); 36 | if (taskResult == null) { 37 | continue; 38 | } 39 | result.addAll(taskResult); 40 | } 41 | return result; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task4/Main.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task4; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.Arrays; 6 | import java.util.List; 7 | 8 | public class Main { 9 | public static void main(String[] args) throws IOException { 10 | String folderName = "resources"; 11 | List keyWords = Arrays.asList("java", "scala"); 12 | 13 | WordCounter wordCounter = new WordCounter(); 14 | Folder folder = Folder.fromDirectory(new File(folderName)); 15 | 16 | for (String documentName : wordCounter.countOccurrencesInParallel(folder, keyWords)) 17 | System.out.println(documentName); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Assignment4/src/com/assignment/task4/WordCounter.java: -------------------------------------------------------------------------------- 1 | package com.assignment.task4; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.ForkJoinPool; 5 | 6 | public class WordCounter { 7 | 8 | public static String[] wordsIn(String line) { 9 | return line.trim().split("(\\s|\\p{Punct})+"); 10 | } 11 | 12 | public static Long occurrencesCount(Document document, List searchedWords) { 13 | long count = 0; 14 | for (String line : document.getLines()) { 15 | for (String word : wordsIn(line)) { 16 | if (searchedWords.contains(word)) { 17 | count = count + 1; 18 | } 19 | } 20 | } 21 | return count; 22 | } 23 | 24 | private final ForkJoinPool forkJoinPool = 25 | new ForkJoinPool(Runtime.getRuntime().availableProcessors()); 26 | 27 | public List countOccurrencesInParallel(Folder folder, List searchedWords) { 28 | return forkJoinPool.invoke(new FolderSearchTask(folder, searchedWords)); 29 | } 30 | 31 | public Long countOccurrencesOnSingleThread(Folder folder, List searchedWords) { 32 | long count = 0; 33 | for (Folder subFolder : folder.getSubFolders()) { 34 | count = count + countOccurrencesOnSingleThread(subFolder, searchedWords); 35 | } 36 | for (Document document : folder.getDocuments()) { 37 | count = count + occurrencesCount(document, searchedWords); 38 | } 39 | return count; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Assignment5/Assignment5.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Assignment5/src/com/assignment/Create.java: -------------------------------------------------------------------------------- 1 | package com.assignment; 2 | 3 | public class Create extends Element { 4 | 5 | public Create(double delay) { 6 | super(delay); 7 | } 8 | 9 | @Override 10 | public void outAct() { 11 | super.outAct(); 12 | super.setTnext(super.getTcurr() + super.getDelay()); 13 | super.getNextElement().inAct(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Assignment5/src/com/assignment/Element.java: -------------------------------------------------------------------------------- 1 | package com.assignment; 2 | 3 | public class Element { 4 | private String name; 5 | private double tnext; 6 | private double delayMean, delayDev; 7 | private String distribution; 8 | private int quantity; 9 | private double tcurr; 10 | private int state; 11 | private Element nextElement; 12 | private static int nextId = 0; 13 | private int id; 14 | 15 | public Element() { 16 | 17 | tnext = 0.0; 18 | delayMean = 1.0; 19 | distribution = "exp"; 20 | tcurr = tnext; 21 | state = 0; 22 | nextElement = null; 23 | id = nextId; 24 | nextId++; 25 | name = "element" + id; 26 | } 27 | 28 | public Element(double delay) { 29 | name = "anonymus"; 30 | tnext = 0.0; 31 | delayMean = delay; 32 | distribution = ""; 33 | tcurr = tnext; 34 | state = 0; 35 | nextElement = null; 36 | id = nextId; 37 | nextId++; 38 | name = "element" + id; 39 | } 40 | 41 | public Element(String nameOfElement, double delay) { 42 | name = nameOfElement; 43 | tnext = 0.0; 44 | delayMean = delay; 45 | distribution = "exp"; 46 | tcurr = tnext; 47 | state = 0; 48 | nextElement = null; 49 | id = nextId; 50 | nextId++; 51 | name = "element" + id; 52 | } 53 | 54 | public double getDelay() { 55 | double delay = getDelayMean(); 56 | if ("exp".equalsIgnoreCase(getDistribution())) { 57 | delay = FunRand.Exp(getDelayMean()); 58 | } else { 59 | if ("norm".equalsIgnoreCase(getDistribution())) { 60 | delay = FunRand.Norm(getDelayMean(), getDelayDev()); 61 | } else { 62 | if ("unif".equalsIgnoreCase(getDistribution())) { 63 | delay = FunRand.Unif(getDelayMean(), getDelayDev()); 64 | } else { 65 | if ("".equalsIgnoreCase(getDistribution())) delay = getDelayMean(); 66 | } 67 | } 68 | } 69 | return delay; 70 | } 71 | 72 | public double getDelayDev() { 73 | return delayDev; 74 | } 75 | 76 | public void setDelayDev(double delayDev) { 77 | this.delayDev = delayDev; 78 | } 79 | 80 | public String getDistribution() { 81 | return distribution; 82 | } 83 | 84 | public void setDistribution(String distribution) { 85 | this.distribution = distribution; 86 | } 87 | 88 | public int getQuantity() { 89 | return quantity; 90 | } 91 | 92 | public double getTcurr() { 93 | return tcurr; 94 | } 95 | 96 | public void setTcurr(double tcurr) { 97 | this.tcurr = tcurr; 98 | } 99 | 100 | public int getState() { 101 | return state; 102 | } 103 | 104 | public void setState(int state) { 105 | this.state = state; 106 | } 107 | 108 | public Element getNextElement() { 109 | return nextElement; 110 | } 111 | 112 | public void setNextElement(Element nextElement) { 113 | this.nextElement = nextElement; 114 | } 115 | 116 | public void inAct() {} 117 | 118 | public void outAct() { 119 | quantity++; 120 | } 121 | 122 | public double getTnext() { 123 | return tnext; 124 | } 125 | 126 | public void setTnext(double tnext) { 127 | this.tnext = tnext; 128 | } 129 | 130 | public double getDelayMean() { 131 | return delayMean; 132 | } 133 | 134 | public void setDelayMean(double delayMean) { 135 | this.delayMean = delayMean; 136 | } 137 | 138 | public int getId() { 139 | return id; 140 | } 141 | 142 | public void setId(int id) { 143 | this.id = id; 144 | } 145 | 146 | public void printResult() { 147 | System.out.println(getName() + " quantity = " + quantity); 148 | } 149 | 150 | public void printInfo() { 151 | System.out.println( 152 | getName() + " state= " + state + " quantity = " + quantity + " tnext= " + tnext); 153 | } 154 | 155 | public String getName() { 156 | return name; 157 | } 158 | 159 | public void setName(String name) { 160 | this.name = name; 161 | } 162 | 163 | public void doStatistics(double delta) {} 164 | } 165 | -------------------------------------------------------------------------------- /Assignment5/src/com/assignment/FunRand.java: -------------------------------------------------------------------------------- 1 | package com.assignment; 2 | 3 | import java.util.Random; 4 | 5 | public class FunRand { 6 | 7 | /** 8 | * Generates a random value according to an exponential distribution 9 | * 10 | * @param timeMean mean value 11 | * @return a random value according to an exponential distribution 12 | */ 13 | public static double Exp(double timeMean) { 14 | double a = 0; 15 | while (a == 0) { 16 | a = Math.random(); 17 | } 18 | a = -timeMean * Math.log(a); 19 | 20 | return a; 21 | } 22 | 23 | /** 24 | * Generates a random value according to a uniform distribution 25 | * 26 | * @param timeMin 27 | * @param timeMax 28 | * @return a random value according to a uniform distribution 29 | */ 30 | public static double Unif(double timeMin, double timeMax) { 31 | double a = 0; 32 | while (a == 0) { 33 | a = Math.random(); 34 | } 35 | a = timeMin + a * (timeMax - timeMin); 36 | 37 | return a; 38 | } 39 | 40 | /** 41 | * Generates a random value according to a normal (Gauss) distribution 42 | * 43 | * @param timeMean 44 | * @param timeDeviation 45 | * @return a random value according to a normal (Gauss) distribution 46 | */ 47 | public static double Norm(double timeMean, double timeDeviation) { 48 | double a; 49 | Random r = new Random(); 50 | a = timeMean + timeDeviation * r.nextGaussian(); 51 | 52 | return a; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Assignment5/src/com/assignment/Model.java: -------------------------------------------------------------------------------- 1 | package com.assignment; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Model { 6 | 7 | private ArrayList list = new ArrayList<>(); 8 | double tnext, tcurr; 9 | int event; 10 | 11 | public Model(ArrayList elements) { 12 | list = elements; 13 | tnext = 0.0; 14 | event = 0; 15 | tcurr = tnext; 16 | } 17 | 18 | public void simulate(double time) { 19 | 20 | while (tcurr < time) { 21 | tnext = Double.MAX_VALUE; 22 | for (Element e : list) { 23 | if (e.getTnext() < tnext) { 24 | tnext = e.getTnext(); 25 | event = e.getId(); 26 | } 27 | } 28 | System.out.println( 29 | "\nIt's time for event in " + list.get(event).getName() + ", time = " + tnext); 30 | for (Element e : list) { 31 | e.doStatistics(tnext - tcurr); 32 | } 33 | tcurr = tnext; 34 | for (Element e : list) { 35 | e.setTcurr(tcurr); 36 | } 37 | list.get(event).outAct(); 38 | for (Element e : list) { 39 | if (e.getTnext() == tcurr) { 40 | e.outAct(); 41 | } 42 | } 43 | printInfo(); 44 | } 45 | printResult(); 46 | } 47 | 48 | public void printInfo() { 49 | for (Element e : list) { 50 | e.printInfo(); 51 | } 52 | } 53 | 54 | public void printResult() { 55 | System.out.println("\n-------------RESULTS-------------"); 56 | for (Element e : list) { 57 | e.printResult(); 58 | if (e instanceof Process) { 59 | Process p = (Process) e; 60 | System.out.println( 61 | "mean length of queue = " 62 | + p.getMeanQueue() / tcurr 63 | + "\nfailure probability = " 64 | + p.getFailure() / (double) p.getQuantity()); 65 | } 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Assignment5/src/com/assignment/Process.java: -------------------------------------------------------------------------------- 1 | package com.assignment; 2 | 3 | public class Process extends Element { 4 | 5 | private int queue, maxqueue, failure; 6 | private double meanQueue; 7 | 8 | public Process(double delay) { 9 | super(delay); 10 | queue = 0; 11 | maxqueue = Integer.MAX_VALUE; 12 | meanQueue = 0.0; 13 | } 14 | 15 | @Override 16 | public void inAct() { 17 | if (super.getState() == 0) { 18 | super.setState(1); 19 | super.setTnext(super.getTcurr() + super.getDelay()); 20 | } else { 21 | if (getQueue() < getMaxqueue()) { 22 | setQueue(getQueue() + 1); 23 | } else { 24 | failure++; 25 | } 26 | } 27 | } 28 | 29 | @Override 30 | public void outAct() { 31 | super.outAct(); 32 | super.setTnext(Double.MAX_VALUE); 33 | super.setState(0); 34 | 35 | if (getQueue() > 0) { 36 | setQueue(getQueue() - 1); 37 | super.setState(1); 38 | super.setTnext(super.getTcurr() + super.getDelay()); 39 | } 40 | } 41 | 42 | public int getFailure() { 43 | return failure; 44 | } 45 | 46 | public int getQueue() { 47 | return queue; 48 | } 49 | 50 | public void setQueue(int queue) { 51 | this.queue = queue; 52 | } 53 | 54 | public int getMaxqueue() { 55 | return maxqueue; 56 | } 57 | 58 | public void setMaxqueue(int maxqueue) { 59 | this.maxqueue = maxqueue; 60 | } 61 | 62 | @Override 63 | public void printInfo() { 64 | super.printInfo(); 65 | System.out.println("failure = " + this.getFailure()); 66 | } 67 | 68 | @Override 69 | public void doStatistics(double delta) { 70 | meanQueue = getMeanQueue() + queue * delta; 71 | } 72 | 73 | public double getMeanQueue() { 74 | return meanQueue; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /Assignment5/src/com/assignment/SimModel.java: -------------------------------------------------------------------------------- 1 | package com.assignment; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class SimModel { 6 | 7 | public static void main(String[] args) { 8 | Create c = new Create(2.0); 9 | Process p = new Process(1.0); 10 | System.out.println("id0 = " + c.getId() + " id1=" + p.getId()); 11 | c.setNextElement(p); 12 | p.setMaxqueue(5); 13 | c.setName("CREATOR"); 14 | p.setName("PROCESSOR"); 15 | c.setDistribution("exp"); 16 | p.setDistribution("exp"); 17 | 18 | ArrayList list = new ArrayList<>(); 19 | list.add(c); 20 | list.add(p); 21 | Model model = new Model(list); 22 | model.simulate(1000.0); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Assignment6/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.17) 2 | project(Assignment6) 3 | 4 | set(CMAKE_CXX_STANDARD 14) 5 | include_directories(/usr/local/openmpi/include/mpi/) 6 | 7 | set(CMAKE_C_COMPILER "/usr/local/openmpi/bin/mpicc") 8 | set(CMAKE_CXX_COMPILER "/usr/local/openmpi/bin/mpic++") 9 | 10 | add_executable(Assignment6 src/task2/main.cpp) -------------------------------------------------------------------------------- /Assignment6/Makefile: -------------------------------------------------------------------------------- 1 | TARGET := main 2 | SRC_DIR := src 3 | MY_PROJECT_BASE_DIRECTORY := /home/kryvokhyzha/IdeaProjects/parallel-and-distributed-computing/Assignment6 4 | SRC_DIR := $(MY_PROJECT_BASE_DIRECTORY)/src 5 | BUILD_DIR := $(MY_PROJECT_BASE_DIRECTORY)/build 6 | 7 | init: 8 | if [ -d $(BUILD_DIR) ]; then \ 9 | echo ; \ 10 | else \ 11 | mkdir $(BUILD_DIR); \ 12 | fi && \ 13 | if [ -d $(SRC_DIR) ]; then \ 14 | echo ; \ 15 | else \ 16 | mkdir $(SRC_DIR); \ 17 | fi 18 | build_main: 19 | mpic++ -o $(BUILD_DIR)/$(TARGET).o $(SRC_DIR)/$(TASK)/$(TARGET).cpp 20 | run: 21 | mpirun --hostfile hostfile $(BUILD_DIR)/$(TARGET).o 22 | build_and_run: 23 | make init && make build_main TASk=$(TASK) && make run -------------------------------------------------------------------------------- /Assignment6/hostfile: -------------------------------------------------------------------------------- 1 | localhost slots=8 -------------------------------------------------------------------------------- /Assignment6/src/task1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "mpi.h" 5 | #define NRA 1000 6 | /* number of rows in matrix A */ 7 | #define NCA 1000 8 | /* number of columns in matrix A */ 9 | #define NCB 1000 10 | /* number of columns in matrix B */ 11 | #define MASTER 0 12 | /* taskid of first task */ 13 | #define FROM_MASTER 1 /* setting a message type */ 14 | #define FROM_WORKER 10 /* setting a message type */ 15 | 16 | double **alloc_2d(int rows, int cols) { 17 | /*allocate a continuous chunk*/ 18 | double *mem = (double *)malloc(rows * cols * sizeof(double)); 19 | double **A = (double **)malloc(rows * sizeof(double *)); 20 | 21 | A[0] = mem; 22 | /*manually split it into rows*/ 23 | for (int i = 1; i < rows; i++) A[i] = A[i - 1] + cols; 24 | 25 | return A; 26 | } 27 | 28 | void free_memory(double **arr) { 29 | free(arr[0]); 30 | free(arr); 31 | } 32 | 33 | int main(int argc, char *argv[]) { 34 | int numtasks, taskid, numworkers, source, dest, rows, 35 | /* rows of matrix A sent to each worker */ 36 | averow, extra, offset, i, j, k; 37 | 38 | double **a = alloc_2d(NRA, NCA); /* matrix A to be multiplied */ 39 | double **b = alloc_2d(NCA, NCB); /* matrix B to be multiplied */ 40 | double **c = alloc_2d(NRA, NCB); /* result matrix C */ 41 | 42 | MPI_Init(&argc, &argv); 43 | 44 | MPI_Status status; 45 | 46 | MPI_Comm_size(MPI_COMM_WORLD, &numtasks); 47 | MPI_Comm_rank(MPI_COMM_WORLD, &taskid); 48 | 49 | if (numtasks < 2) { 50 | printf("Need at least two MPI tasks. Quitting...\n"); 51 | MPI_Abort(MPI_COMM_WORLD, -1); 52 | exit(1); 53 | } 54 | 55 | numworkers = numtasks - 1; 56 | 57 | if (taskid == MASTER) { 58 | printf("mpi_mm has started with %d tasks (task1).\n", numtasks); 59 | 60 | for (i = 0; i < NRA; i++) 61 | for (j = 0; j < NCA; j++) a[i][j] = 10; 62 | for (i = 0; i < NCA; i++) 63 | for (j = 0; j < NCB; j++) b[i][j] = 10; 64 | 65 | double t1 = MPI_Wtime(); 66 | 67 | averow = NRA / numworkers; 68 | extra = NRA % numworkers; 69 | offset = 0; 70 | 71 | for (dest = 1; dest <= numworkers; dest++) { 72 | rows = (dest <= extra) ? averow + 1 : averow; 73 | printf("Sending %d rows to task %d offset=%d\n", rows, dest, offset); 74 | 75 | MPI_Send(&offset, 1, MPI_INT, dest, FROM_MASTER, MPI_COMM_WORLD); 76 | MPI_Send(&rows, 1, MPI_INT, dest, FROM_MASTER + 1, MPI_COMM_WORLD); 77 | MPI_Send(a[offset], rows * NCA, MPI_DOUBLE, dest, FROM_MASTER + 2, 78 | MPI_COMM_WORLD); 79 | MPI_Send(b[0], NCA * NCB, MPI_DOUBLE, dest, FROM_MASTER + 3, 80 | MPI_COMM_WORLD); 81 | 82 | offset = offset + rows; 83 | } 84 | 85 | /* Receive results from worker tasks */ 86 | for (source = 1; source <= numworkers; source++) { 87 | MPI_Recv(&offset, 1, MPI_INT, source, FROM_WORKER, MPI_COMM_WORLD, 88 | &status); 89 | MPI_Recv(&rows, 1, MPI_INT, source, FROM_WORKER + 1, MPI_COMM_WORLD, 90 | &status); 91 | MPI_Recv(c[offset], rows * NCB, MPI_DOUBLE, source, FROM_WORKER + 2, 92 | MPI_COMM_WORLD, &status); 93 | 94 | printf("Received results from task %d\n", source); 95 | } 96 | 97 | /* Print results */ 98 | /* 99 | printf("****\n"); 100 | printf("Result Matrix:\n"); 101 | 102 | for (i = 0; i < NRA; i++) 103 | { 104 | printf("\n"); 105 | for (j = 0; j < NCB; j++) printf("%6.2f ", c[i][j]); 106 | } 107 | 108 | printf("\n********\n"); 109 | printf("Done.\n");*/ 110 | 111 | t1 = MPI_Wtime() - t1; 112 | 113 | printf("\nExecution time: %.2f\n", t1); 114 | } 115 | /******** worker task *****************/ 116 | else { /* if (taskid > MASTER) */ 117 | MPI_Recv(&offset, 1, MPI_INT, MASTER, FROM_MASTER, MPI_COMM_WORLD, &status); 118 | MPI_Recv(&rows, 1, MPI_INT, MASTER, FROM_MASTER + 1, MPI_COMM_WORLD, 119 | &status); 120 | MPI_Recv(a[0], rows * NCA, MPI_DOUBLE, MASTER, FROM_MASTER + 2, 121 | MPI_COMM_WORLD, &status); 122 | MPI_Recv(b[0], NCA * NCB, MPI_DOUBLE, MASTER, FROM_MASTER + 3, 123 | MPI_COMM_WORLD, &status); 124 | 125 | for (k = 0; k < NCB; k++) 126 | for (i = 0; i < rows; i++) { 127 | c[i][k] = 0.0; 128 | for (j = 0; j < NCA; j++) c[i][k] = c[i][k] + a[i][j] * b[j][k]; 129 | } 130 | 131 | MPI_Send(&offset, 1, MPI_INT, MASTER, FROM_WORKER, MPI_COMM_WORLD); 132 | MPI_Send(&rows, 1, MPI_INT, MASTER, FROM_WORKER + 1, MPI_COMM_WORLD); 133 | MPI_Send(c[0], rows * NCB, MPI_DOUBLE, MASTER, FROM_WORKER + 2, 134 | MPI_COMM_WORLD); 135 | } 136 | 137 | free_memory(a); 138 | free_memory(b); 139 | free_memory(c); 140 | 141 | MPI_Finalize(); 142 | } -------------------------------------------------------------------------------- /Assignment6/src/task2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "mpi.h" 5 | #define NRA 1000 6 | /* number of rows in matrix A */ 7 | #define NCA 1000 8 | /* number of columns in matrix A */ 9 | #define NCB 1000 10 | /* number of columns in matrix B */ 11 | #define MASTER 0 12 | /* taskid of first task */ 13 | #define FROM_MASTER 1 /* setting a message type */ 14 | #define FROM_WORKER 10 /* setting a message type */ 15 | 16 | double **alloc_2d(int rows, int cols) { 17 | /*allocate a continuous chunk*/ 18 | double *mem = (double *)malloc(rows * cols * sizeof(double)); 19 | double **A = (double **)malloc(rows * sizeof(double *)); 20 | 21 | A[0] = mem; 22 | /*manually split it into rows*/ 23 | for (int i = 1; i < rows; i++) A[i] = A[i - 1] + cols; 24 | 25 | return A; 26 | } 27 | 28 | void free_memory(double **arr) { 29 | free(arr[0]); 30 | free(arr); 31 | } 32 | 33 | int main(int argc, char *argv[]) { 34 | int numtasks, taskid, numworkers, source, dest, rows, 35 | /* rows of matrix A sent to each worker */ 36 | averow, extra, offset, i, j, k; 37 | 38 | double **a = alloc_2d(NRA, NCA); /* matrix A to be multiplied */ 39 | double **b = alloc_2d(NCA, NCB); /* matrix B to be multiplied */ 40 | double **c = alloc_2d(NRA, NCB); /* result matrix C */ 41 | 42 | MPI_Init(&argc, &argv); 43 | 44 | MPI_Comm_size(MPI_COMM_WORLD, &numtasks); 45 | MPI_Comm_rank(MPI_COMM_WORLD, &taskid); 46 | 47 | if (numtasks < 2) { 48 | printf("Need at least two MPI tasks. Quitting...\n"); 49 | MPI_Abort(MPI_COMM_WORLD, -1); 50 | exit(1); 51 | } 52 | 53 | numworkers = numtasks - 1; 54 | 55 | if (taskid == MASTER) { 56 | printf("mpi_mm has started with %d tasks (task 2).\n", numtasks); 57 | 58 | for (i = 0; i < NRA; i++) 59 | for (j = 0; j < NCA; j++) a[i][j] = 10; 60 | for (i = 0; i < NCA; i++) 61 | for (j = 0; j < NCB; j++) b[i][j] = 10; 62 | 63 | double t1 = MPI_Wtime(); 64 | 65 | averow = NRA / numworkers; 66 | extra = NRA % numworkers; 67 | offset = 0; 68 | 69 | MPI_Status recv_status1[numworkers * 2], recv_status2[numworkers]; 70 | MPI_Request send_req[numworkers * 4], recv_req1[numworkers * 2], 71 | recv_req2[numworkers]; 72 | 73 | for (dest = 1; dest <= numworkers; dest++) { 74 | rows = (dest <= extra) ? averow + 1 : averow; 75 | 76 | printf("Sending %d rows to task %d offset=%d\n", rows, dest, offset); 77 | MPI_Isend(&offset, 1, MPI_INT, dest, FROM_MASTER, MPI_COMM_WORLD, 78 | &send_req[(dest - 1) * 4]); 79 | MPI_Isend(&rows, 1, MPI_INT, dest, FROM_MASTER + 1, MPI_COMM_WORLD, 80 | &send_req[(dest - 1) * 4 + 1]); 81 | MPI_Isend(a[offset], rows * NCA, MPI_DOUBLE, dest, FROM_MASTER + 2, 82 | MPI_COMM_WORLD, &send_req[(dest - 1) * 4 + 2]); 83 | MPI_Isend(b[0], NCA * NCB, MPI_DOUBLE, dest, FROM_MASTER + 3, 84 | MPI_COMM_WORLD, &send_req[(dest - 1) * 4 + 3]); 85 | 86 | offset = offset + rows; 87 | } 88 | 89 | // MPI_Waitall(numworkers * 4, &send_req[0], &send_status[0]); 90 | 91 | /* Receive results from worker tasks */ 92 | int offsets_arr[numworkers]; 93 | int rows_arr[numworkers]; 94 | 95 | for (source = 1; source <= numworkers; source++) { 96 | MPI_Irecv(&offsets_arr[source - 1], 1, MPI_INT, source, FROM_WORKER, 97 | MPI_COMM_WORLD, &recv_req1[(source - 1) * 2]); 98 | MPI_Irecv(&rows_arr[source - 1], 1, MPI_INT, source, FROM_WORKER + 1, 99 | MPI_COMM_WORLD, &recv_req1[(source - 1) * 2 + 1]); 100 | } 101 | 102 | MPI_Waitall(numworkers * 2, &recv_req1[0], &recv_status1[0]); 103 | 104 | for (source = 1; source <= numworkers; source++) { 105 | MPI_Irecv(c[offsets_arr[source - 1]], rows_arr[source - 1] * NCB, 106 | MPI_DOUBLE, source, FROM_WORKER + 2, MPI_COMM_WORLD, 107 | &recv_req2[source - 1]); 108 | printf("Received results from task %d\n", source); 109 | } 110 | 111 | MPI_Waitall(numworkers, &recv_req2[0], &recv_status2[0]); 112 | 113 | /* Print results */ 114 | /*printf("****\n"); 115 | printf("Result Matrix:\n"); 116 | 117 | for (i = 0; i < NRA; i++) 118 | { 119 | printf("\n"); 120 | for (j = 0; j < NCB; j++) printf("%6.2f ", c[i][j]); 121 | } 122 | 123 | printf("\n********\n"); 124 | printf("Done.\n");*/ 125 | 126 | t1 = MPI_Wtime() - t1; 127 | printf("\nExecution time: %.2f\n", t1); 128 | } 129 | /******** worker task *****************/ 130 | else { /* if (taskid > MASTER) */ 131 | MPI_Status recv_status[4]; 132 | MPI_Request send_req[3], recv_req[4]; 133 | 134 | MPI_Irecv(&offset, 1, MPI_INT, MASTER, FROM_MASTER, MPI_COMM_WORLD, 135 | &recv_req[0]); 136 | MPI_Irecv(&rows, 1, MPI_INT, MASTER, FROM_MASTER + 1, MPI_COMM_WORLD, 137 | &recv_req[1]); 138 | MPI_Irecv(b[0], NCA * NCB, MPI_DOUBLE, MASTER, FROM_MASTER + 3, 139 | MPI_COMM_WORLD, &recv_req[3]); 140 | 141 | MPI_Wait(&recv_req[0], &recv_status[0]); 142 | MPI_Wait(&recv_req[1], &recv_status[1]); 143 | 144 | MPI_Isend(&offset, 1, MPI_INT, MASTER, FROM_WORKER, MPI_COMM_WORLD, 145 | &send_req[0]); 146 | MPI_Isend(&rows, 1, MPI_INT, MASTER, FROM_WORKER + 1, MPI_COMM_WORLD, 147 | &send_req[1]); 148 | 149 | MPI_Irecv(a[0], rows * NCA, MPI_DOUBLE, MASTER, FROM_MASTER + 2, 150 | MPI_COMM_WORLD, &recv_req[2]); 151 | 152 | MPI_Wait(&recv_req[2], &recv_status[2]); 153 | MPI_Wait(&recv_req[3], &recv_status[3]); 154 | 155 | for (k = 0; k < NCB; k++) 156 | for (i = 0; i < rows; i++) { 157 | c[i][k] = 0.0; 158 | for (j = 0; j < NCA; j++) c[i][k] = c[i][k] + a[i][j] * b[j][k]; 159 | } 160 | 161 | MPI_Isend(c[0], rows * NCB, MPI_DOUBLE, MASTER, FROM_WORKER + 2, 162 | MPI_COMM_WORLD, &send_req[2]); 163 | 164 | MPI_Status st; 165 | MPI_Wait(&send_req[2], &st); 166 | } 167 | 168 | free_memory(a); 169 | free_memory(b); 170 | free_memory(c); 171 | 172 | MPI_Finalize(); 173 | } -------------------------------------------------------------------------------- /AssignmentsList.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kryvokhyzha/parallel-and-distributed-computing/43904c0965e298104314a9a9638e80d95fa8239d/AssignmentsList.pdf -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Roman Kryvokhyzha 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | install_dep: 2 | sudo apt install clang clang-format clang-tidy uncrustify cppcheck 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # parallel-and-distributed-computing 2 | This repository contains PDC course assignments. 3 | 4 | ## Assignment 1 5 | **Розробка потоків та 6 | дослідження пріоритету запуску потоків** 7 | 1. Реалізуйте програму імітації руху більярдних кульок, в якій рух кожної кульки відтворюється в окремому потоці (див. презентацію «Створення та запуск потоків в java» та приклад). Спостерігайте роботу програми при збільшенні кількості кульок. Поясніть результати спостереження. Опишіть переваги потокової архітектури програм. 8 | 2. Модифікуйте програму так, щоб при потраплянні в «лузу» кульки зникали, а відповідний потік завершував свою роботу. Кількість кульок, яка потрапила в «лузу», має динамічно відображатись у текстовому полі інтерфейсу програми. 9 | 3. Виконайте дослідження параметру priority потоку. Для цього модифікуйте програму «Більярдна кулька» так, щоб кульки червоного кольору створювались з вищим пріоритетом потоку, в якому вони виконують рух, ніж кульки синього кольору. Спостерігайте рух червоних та синіх кульок при збільшенні загальної кількості кульок. Проведіть такий експеримент. Створіть багато кульок синього кольору (з низьким пріоритетом) і одну червоного кольору, які починають рух в одному й тому ж самому місці більярдного стола, в одному й тому ж самому напрямку та з однаковою швидкістю. Спостерігайте рух кульки з більшим пріоритетом. Повторіть експеримент кілька разів, значно збільшуючи кожного разу кількість кульок синього кольору. Зробіть висновки про вплив пріоритету потоку на його роботу в залежності від загальної кількості потоків. 10 | 4. Побудуйте ілюстрацію для методу join() класу Thread з використанням руху більярдних кульок різного кольору. Поясніть результат, який спостерігається. 11 | 5. Створіть два потоки, один з яких виводить на консоль символ ‘-‘, а інший – символ ‘|’. Запустіть потоки в основній програмі так, щоб вони виводили свої символи в рядок. Виведіть на консоль 100 таких рядків. Поясніть виведений результат. 10 балів. Використовуючи найпростіші методи управління потоками, добийтесь почергового виведення на консоль символів. 12 | 6. + Створіть клас Counter з методами increment() та decrement(), які збільшують та зменшують значення лічильника відповідно. Створіть два потоки, один з яких збільшує 100000 разів значення лічильника, а інший – зменшує 100000 разів значення лічильника. Запустіть потоки на одночасне виконання. Спостерігайте останнє значення лічильника. Поясніть результат. 13 | + 10 балів. Використовуючи синхронізований доступ, добийтесь правильної роботи лічильника при одночасній роботі з ним двох і більше потоків. Опрацюйте використання таких способів синхронізації: синхронізований метод, синхронізований блок, блокування об’єкта. Порівняйте способи синхронізації. 14 | 15 | ## Assignment 2 16 | **Розробка паралельних алгоритмів множення матриць та дослідження їх ефективності** 17 | 1. Реалізуйте стрічковий алгоритм множення матриць. Результат множення записуйте в об’єкт класу Result. 18 | 2. Реалізуйте алгоритм Фокса множення матриць. 19 | 3. Виконайте експерименти, варіюючи розмірність матриць, які перемножуються, для обох алгоритмів, та реєструючи час виконання алгоритму. Порівняйте результати дослідження ефективності обох алгоритмів. 20 | 4. Виконайте експерименти, варіюючи кількість потоків, що використовується для паралельного множення матриць, та реєструючи час виконання. Порівняйте результати дослідження ефективності обох алгоритмів. 21 | 22 | ## Assignment 3 23 | **Розробка паралельних програм з використанням механізмів синхронізації: синхронізовані методи, локери, спеціальні типи** 24 | 1. Реалізуйте програмний код, даний у лістингу, та протестуйте його при різних значеннях параметрів. Модифікуйте програму, використовуючи методи управління потоками, так, щоб її робота була завжди коректною. Запропонуйте три різних варіанти управління. 25 | 2. Реалізуйте приклад [Producer-Consumer application](https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html). Модифікуйте масив даних цієї програми, які читаються, у масив чисел заданого розміру (100, 1000 або 5000) та протестуйте програму. Зробіть висновок про правильність роботи програми. 26 | 3. Реалізуйте роботу електронного журналу групи, в якому зберігаються оцінки з однієї дисципліни трьох груп студентів. Кожного тижня лектор і його 3 асистенти виставляють оцінки з дисципліни за 100-бальною шкалою. 27 | 4. Зробіть висновки про використання методів управління потоками в java. 28 | 29 | ## Assignment 4 30 | **Розробка паралельних програм з використанням пулів потоків, екзекьюторів та ForkJoinFramework** 31 | 1. + Побудуйте алгоритм статистичного аналізу тексту та визначте характеристики випадкової величини «довжина слова в символах» з використанням ForkJoinFramework. 32 | + Дослідіть побудований алгоритм аналізу текстових документів на ефективність експериментально. 33 | 2. Реалізуйте один з алгоритмів комп’ютерного практикуму 2 або 3 з використанням ForkJoinFramework та визначте прискорення, яке отримане за рахунок використання ForkJoinFramework. 34 | 3. Розробіть та реалізуйте алгоритм пошуку спільних слів в текстових документах з використанням ForkJoinFramework. 35 | 4. Розробіть та реалізуйте алгоритм пошуку текстових документів, які відповідають заданим ключовим словам (належать до області «Інформаційні технології»), з використанням ForkJoinFramework. 36 | 37 | ## Assignment 5 38 | **Застосування високорівневих засобів паралельного програмування для побудови алгоритмів імітації та дослідження їх ефективності** 39 | 1. З використанням пулу потоків побудувати алгоритм імітації багатоканальної системи масового обслуговування з обмеженою чергою, відтворюючи функціонування кожного каналу обслуговування в окремому потоці. Результатом виконання алгоритму є розраховані значення середньої довжини черги та ймовірності відмови. 40 | 2. З використанням багатопоточної технології організувати паралельне виконання прогонів імітаційної моделі СМО для отримання статистично значимої оцінки середньої довжини черги та ймовірності відмови. 41 | 3. Виводити результати імітаційного моделювання (стан моделі та чисельні значення вихідних змінних) в окремому потоці для динамічного відтворення імітації системи. 42 | 4. Розробити модель паралельних обчислень для одного з алгоритмів, побудованих при виконанні лабораторних робіт 2-5 з використанням стохастичної мережі Петрі. 15 балів. Дослідити на моделі зростання часу виконання паралельного алгоритму при збільшенні розміру оброблюваних даних. 43 | 5. Побудувати теоретичні оцінки показників ефективності для одного з алгоритмів практичних завдань 2-5 44 | 45 | ## Assignment 6 46 | **Розробка паралельного алгоритму множення матриць з використанням МРІ-методів обміну повідомленнями «один-до-одного» та дослідження його ефективності** 47 | 1. Ознайомитись з методами блокуючого та неблокуючого обміну повідомленнями типу point-to-point (див. лекцію та документацію стандарту MPI) 48 | 2. Реалізувати алгоритм паралельного множення матриць з використанням розподілених обчислень в OpenMPI з використанням методів блокуючого обміну повідомленнями (лістинг 1) 49 | 3. Реалізувати алгоритм паралельного множення матриць з використанням розподілених обчислень в OpenMPI з використанням методів неблокуючого обміну повідомленнями. 50 | 4. Дослідити ефективність розподіленого обчислення алгоритму множення матриць при збільшенні розміру матриць та при збільшенні кількості вузлів, на яких здійснюється запуск програми. Порівняйте ефективність алгоритму при використанні блокуючих та неблокуючих методів обміну повідомленнями. 51 | 52 | ## Assignment 7 53 | **Розробка паралельного алгоритму множення матриць з використанням МРІ-методів колективного обміну повідомленнями («один-до-багатьох», «багато-до-одного», «багато- до-багатьох») та дослідження його ефективності** 54 | 55 | **** 56 | 57 | ## Sources 58 | + [The Java Tutorials Lesson: Concurrency](https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html) 59 | + [FastMPJ User’s Guide](http://gac.udc.es/~rreye/fastmpj/doc/UsersGuide.pdf) 60 | + [Foster I. Designing and Building Parallel Programs](http://www.mcs.anl.gov/~itf/dbpp/text/book.html) 61 | -------------------------------------------------------------------------------- /mpj-examples/HelloWorldParallel.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import mpi.*; 4 | 5 | public class HelloWorldParallel { 6 | public static void main(String[] args) throws MPIException { 7 | // iнiцiалiзацiя паралельної частини 8 | MPI.Init(args); 9 | // визначення номера процесора 10 | int myrank = MPI.COMM_WORLD.getRank(); 11 | System.out.println("Proc num " + myrank + " Hello World"); 12 | // завершення паралельної частини 13 | MPI.Finalize(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /mpj-examples/MatrixMul4.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import com.mathpar.matrix.*; 4 | import com.mathpar.number.*; 5 | import com.mathpar.parallel.utils.MPITransport; 6 | import java.io.IOException; 7 | import java.util.Random; 8 | import mpi.*; 9 | 10 | public class MatrixMul4 { 11 | public static MatrixS mmultiply(MatrixS a, MatrixS b, MatrixS c, MatrixS d, Ring ring) { 12 | // помножимо a на b, с на d та додамо результати 13 | return (a.multiply(b, ring)).add(c.multiply(d, ring), ring); 14 | } 15 | 16 | public static void main(String[] args) throws MPIException, IOException, ClassNotFoundException { 17 | Ring ring = new Ring("Z[]"); 18 | // iнiцiалiзацiя MPI 19 | MPI.Init(args); 20 | // отримання номера процесора 21 | int rank = MPI.COMM_WORLD.getRank(); 22 | if (rank == 0) { 23 | // програма виконується на нульовому процесорi 24 | int ord = 4; 25 | int den = 10000; 26 | // представник класу випадкового генератора 27 | Random rnd = new Random(); 28 | // ord = розмiр матрицi, den = щiльнiсть 29 | MatrixS A = new MatrixS(ord, ord, den, new int[] {5}, rnd, NumberZ.ONE, ring); 30 | MatrixS B = new MatrixS(ord, ord, den, new int[] {5}, rnd, NumberZ.ONE, ring); 31 | 32 | MatrixS[] DD = new MatrixS[4]; 33 | MatrixS CC = null; 34 | // розбиваємо матрицю A на 4 частини 35 | MatrixS[] AA = A.split(); 36 | // розбиваємо матрицю B на 4 частини 37 | MatrixS[] BB = B.split(); 38 | // вiдправлення вiд нульового процесора масиву Object процесору 1 з iдентифiкатором tag = 1 39 | MPITransport.sendObjectArray(new Object[] {AA[0], BB[1], AA[1], BB[3]}, 0, 4, 1, 1); 40 | // вiдправлення вiд нульового процесора масиву Object процесору 2 з iдентифiкатором tag = 2 41 | MPITransport.sendObjectArray(new Object[] {AA[2], BB[0], AA[3], BB[2]}, 0, 4, 2, 2); 42 | // вiдправлення вiд нульового процесора масиву Object// процесору 3 з iдентифiкатором tag = 3 43 | MPITransport.sendObjectArray(new Object[] {AA[2], BB[1], AA[3], BB[3]}, 0, 4, 3, 3); 44 | // залишаємо один блок нульовому процесору для оброблення 45 | DD[0] = (AA[0].multiply(BB[0], ring)).add(AA[1].multiply(BB[2], ring), ring); 46 | // отримуємо результат вiд першого процесора 47 | DD[1] = (MatrixS) MPITransport.recvObject(1, 1); 48 | System.out.println("recv 1 to 0"); // отримуємо результат вiд другого процесора 49 | DD[2] = (MatrixS) MPITransport.recvObject(2, 2); 50 | System.out.println("recv 2 to 0"); 51 | // отримуємо результат вiд третього процесора 52 | DD[3] = (MatrixS) MPITransport.recvObject(3, 3); 53 | System.out.println("recv 3 to 0"); 54 | // процедура збору матрицi з блокiв DD[i]//(i=0,...,3) 55 | CC = MatrixS.join(DD); 56 | System.out.println("RES= " + CC.toString()); 57 | } else { 58 | // програма виконується на процесорi з номером rank 59 | System.out.println("I’m processor " + rank); 60 | // отримуємо масив Object з блоками матриць вiд нульового процесора 61 | Object[] n = new Object[4]; 62 | MPITransport.recvObjectArray(n, 0, 4, 0, rank); 63 | MatrixS a = (MatrixS) n[0]; 64 | MatrixS b = (MatrixS) n[1]; 65 | MatrixS c = (MatrixS) n[2]; 66 | MatrixS d = (MatrixS) n[3]; 67 | 68 | // перемножуємо та складаємо блоки матриць 69 | MatrixS res = mmultiply(a, b, c, d, ring); 70 | // надсилаємо результат обчислень вiд процесора rank нульовому процесору 71 | System.out.println("res = " + res); 72 | MPITransport.sendObject(res, 0, rank); 73 | // повiдомлення на консоль про те, що результат буде надiслано 74 | System.out.println("send result"); 75 | } 76 | MPI.Finalize(); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /mpj-examples/MatrixMul8.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import com.mathpar.matrix.MatrixS; 4 | import com.mathpar.number.NumberZ; 5 | import com.mathpar.number.Ring; 6 | import com.mathpar.parallel.utils.MPITransport; 7 | import java.io.IOException; 8 | import java.util.Random; 9 | import mpi.MPI; 10 | import mpi.MPIException; 11 | 12 | class MatrixMul8 { 13 | public static void main(String[] args) throws MPIException, IOException, ClassNotFoundException { 14 | Ring ring = new Ring("Z[]"); 15 | MPI.Init(args); 16 | int rank = MPI.COMM_WORLD.getRank(); 17 | if (rank == 0) { 18 | int ord = 8; 19 | int den = 10000; 20 | Random rnd = new Random(); 21 | MatrixS A = new MatrixS(ord, ord, den, new int[] {5}, rnd, NumberZ.ONE, ring); 22 | System.out.println("A = " + A); 23 | MatrixS B = new MatrixS(ord, ord, den, new int[] {5}, rnd, NumberZ.ONE, ring); 24 | System.out.println("B = " + B); 25 | MatrixS D = null; 26 | MatrixS[] AA = A.split(); 27 | MatrixS[] BB = B.split(); 28 | int tag = 0; 29 | MPITransport.sendObjectArray(new Object[] {AA[1], BB[2]}, 0, 2, 1, tag); 30 | MPITransport.sendObjectArray(new Object[] {AA[0], BB[1]}, 0, 2, 2, tag); 31 | MPITransport.sendObjectArray(new Object[] {AA[1], BB[3]}, 0, 2, 3, tag); 32 | MPITransport.sendObjectArray(new Object[] {AA[2], BB[0]}, 0, 2, 4, tag); 33 | MPITransport.sendObjectArray(new Object[] {AA[3], BB[2]}, 0, 2, 5, tag); 34 | MPITransport.sendObjectArray(new Object[] {AA[2], BB[1]}, 0, 2, 6, tag); 35 | MPITransport.sendObjectArray(new Object[] {AA[3], BB[3]}, 0, 2, 7, tag); 36 | MatrixS[] DD = new MatrixS[4]; 37 | DD[0] = (AA[0].multiply(BB[0], ring)).add((MatrixS) MPITransport.recvObject(1, 3), ring); 38 | DD[1] = (MatrixS) MPITransport.recvObject(2, 3); 39 | DD[2] = (MatrixS) MPITransport.recvObject(4, 3); 40 | DD[3] = (MatrixS) MPITransport.recvObject(6, 3); 41 | D = MatrixS.join(DD); 42 | System.out.println("RES = " + D.toString()); 43 | } else { 44 | System.out.println("I'm processor " + rank); 45 | Object[] b = new Object[2]; 46 | MPITransport.recvObjectArray(b, 0, 2, 0, 0); 47 | MatrixS[] a = new MatrixS[b.length]; 48 | for (int i = 0; i < b.length; i++) a[i] = (MatrixS) b[i]; 49 | MatrixS res = a[0].multiply(a[1], ring); 50 | if (rank % 2 == 0) { 51 | MatrixS p = res.add((MatrixS) MPITransport.recvObject(rank + 1, 3), ring); 52 | MPITransport.sendObject(p, 0, 3); 53 | } else { 54 | MPITransport.sendObject(res, rank - 1, 3); 55 | } 56 | } 57 | MPI.Finalize(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /mpj-examples/MultiplyMatrixToVector.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import com.mathpar.matrix.MatrixS; 4 | import com.mathpar.number.*; 5 | import java.io.IOException; 6 | import java.util.Random; 7 | import mpi.MPI; 8 | import mpi.MPIException; 9 | 10 | public class MultiplyMatrixToVector { 11 | public static void main(String[] args) throws MPIException, IOException, ClassNotFoundException { 12 | 13 | Ring ring = new Ring("Z[]"); 14 | MPI.Init(args); 15 | int rank = MPI.COMM_WORLD.getRank(); 16 | int size = MPI.COMM_WORLD.getSize(); 17 | int ord = 16; // matrix size (ord х ord) 18 | int k = ord / size; // the number of rows for each processor 19 | int n = ord - k * (size - 1); // the last portion will be n (less than k) elements ) 20 | if (rank == 0) { 21 | int den = 10000; // for density=100% 22 | Random rnd = new Random(); 23 | MatrixS A = new MatrixS(ord, ord, den, new int[] {5}, rnd, NumberZ.ONE, ring); 24 | System.out.println("Matrix A = " + A.toString()); 25 | VectorS B = new VectorS(ord, den, new int[] {5}, rnd, ring); 26 | System.out.println("Vector B = " + B.toString()); 27 | Element[] result = new Element[ord]; // For resulting vector 28 | for (int j = 1; j < size; j++) { 29 | Element[][] Mj = new Element[k][]; 30 | int[][] colj = new int[k][]; 31 | for (int s = 0; s < k; s++) { 32 | Mj[s] = A.M[s + j * k]; 33 | colj[s] = A.col[s + j * k]; 34 | } 35 | MatrixS Aj = new MatrixS(Mj, colj); 36 | Transport.sendObject(Aj, j, 1); 37 | Transport.sendObject(B, j, 2); 38 | } 39 | Element[][] M0 = new Element[n][]; 40 | int[][] col0 = new int[n][]; 41 | for (int s = 0; s < n; s++) { 42 | M0[s] = A.M[s + (size - 1) * k]; 43 | col0[s] = A.col[s + (size - 1) * k]; 44 | } 45 | MatrixS A0 = new MatrixS(M0, col0); 46 | VectorS V0 = A0.multiplyByColumn(B.transpose(ring), ring); 47 | System.arraycopy(V0.V, 0, result, (size - 1) * k, n); 48 | for (int t = 1; t < size; t++) { 49 | VectorS Vt = (VectorS) Transport.recvObject(t, t); 50 | System.arraycopy(Vt.V, 0, result, (t - 1) * k, k); 51 | } 52 | System.out.println("RESULT: A*B=" + new VectorS(result).toString(ring)); 53 | } else { 54 | MatrixS AA = (MatrixS) Transport.recvObject(0, 1); 55 | System.out.println(" AA(" + rank + ") = " + AA.toString(ring)); 56 | VectorS BB = (VectorS) Transport.recvObject(0, 2); 57 | System.out.println(" BB(" + rank + ") = " + BB.toString(ring)); 58 | VectorS VV = AA.multiplyByColumn(BB.transpose(ring), ring); 59 | System.out.println(" VV(" + rank + ") = " + VV.toString(ring)); 60 | Transport.sendObject(VV, 0, rank); 61 | System.out.println("send result from(" + rank + ")"); 62 | } 63 | MPI.Finalize(); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /mpj-examples/MultiplyVectorToScalar.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import com.mathpar.number.*; 4 | import java.io.IOException; 5 | import java.util.Random; 6 | import mpi.MPI; 7 | import mpi.MPIException; 8 | 9 | public class MultiplyVectorToScalar { 10 | public static void main(String[] args) throws MPIException, IOException, ClassNotFoundException { 11 | 12 | Ring ring = new Ring("Z[]"); 13 | MPI.Init(args); 14 | int rank = MPI.COMM_WORLD.getRank(); 15 | int size = MPI.COMM_WORLD.getSize(); 16 | 17 | int ord = 8; 18 | 19 | Element s = NumberZ.valueOf(5); 20 | 21 | int k = ord / size; 22 | 23 | int n = ord - k * (size - 1); 24 | if (rank == 0) { 25 | int den = 10000; 26 | Random rnd = new Random(); 27 | VectorS B = new VectorS(ord, den, new int[] {5}, rnd, ring); 28 | System.out.println("Vector B = " + B); 29 | 30 | Element[] res0 = new Element[n]; 31 | for (int i = 0; i < n; i++) { 32 | res0[i] = B.V[i].multiply(s, ring); 33 | } 34 | 35 | for (int j = 1; j < size; j++) { 36 | Element[] v = new Element[k]; 37 | System.arraycopy(B.V, n + (j - 1) * k, v, 0, k); 38 | Transport.sendObject(v, j, 100 + j); 39 | } 40 | 41 | Element[] result = new Element[ord]; 42 | System.arraycopy(res0, 0, result, 0, n); 43 | 44 | for (int t = 1; t < size; t++) { 45 | Element[] resRank = (Element[]) Transport.recvObject(t, 100 + t); 46 | System.arraycopy(resRank, 0, result, n + (t - 1) * k, resRank.length); 47 | } 48 | System.out.println("B * S = " + new VectorS(result).toString(ring)); 49 | } else { 50 | 51 | System.out.println("I’m processor " + rank); 52 | 53 | Element[] B = (Element[]) Transport.recvObject(0, 100 + rank); 54 | System.out.println("rank = " + rank + " B = " + Array.toString(B)); 55 | 56 | Element[] result = new Element[k]; 57 | for (int j = 0; j < B.length; j++) { 58 | result[j] = B[j].multiply(s, ring); 59 | } 60 | 61 | Transport.sendObject(result, 0, 100 + rank); 62 | System.out.println("send result"); 63 | } 64 | MPI.Finalize(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /mpj-examples/TestAllGather.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.util.Arrays; 4 | import mpi.MPI; 5 | 6 | public class TestAllGather { 7 | public static void main(String[] args) throws Exception { 8 | // ініціалізація MPI 9 | MPI.Init(args); 10 | // визначення номера процесора 11 | int myrank = MPI.COMM_WORLD.getRank(); 12 | // визначення числа процесорів в групі 13 | int np = MPI.COMM_WORLD.getSize(); 14 | int n = 2; 15 | int[] a = new int[n]; 16 | for (int i = 0; i < n; i++) { 17 | a[i] = myrank * 10 + i; 18 | } 19 | System.out.println("myrank = " + myrank + " : a = " + Arrays.toString(a)); 20 | int[] q = new int[n * np]; 21 | MPI.COMM_WORLD.allGather(a, n, MPI.INT, q, n, MPI.INT); 22 | System.out.println("myrank = " + myrank + " : q = " + Arrays.toString(q)); 23 | // завершення паралельної частини 24 | MPI.Finalize(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /mpj-examples/TestAllGatherv.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.util.Arrays; 4 | import mpi.MPI; 5 | import mpi.MPIException; 6 | 7 | public class TestAllGatherv { 8 | public static void main(String[] args) throws MPIException, InterruptedException { 9 | 10 | // ініціалізація MPI 11 | MPI.Init(args); 12 | // визначення номера процесора 13 | int myrank = MPI.COMM_WORLD.getRank(); 14 | int n = 5; 15 | int[] a = new int[n]; 16 | int np = MPI.COMM_WORLD.getSize(); 17 | for (int i = 0; i < n; i++) { 18 | a[i] = myrank * 10 + i; 19 | } 20 | System.out.println("myrank = " + myrank + ": a = " + Arrays.toString(a)); 21 | int[] q = new int[n * np]; 22 | MPI.COMM_WORLD.allGatherv(a, n, MPI.INT, q, new int[] {n, n}, new int[] {5, 0}, MPI.INT); 23 | 24 | System.out.println("myrank = " + myrank + ": q = " + Arrays.toString(q)); 25 | // завершення паралельної частини 26 | MPI.Finalize(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /mpj-examples/TestAllReduce.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.util.Arrays; 4 | import mpi.MPI; 5 | import mpi.MPIException; 6 | 7 | public class TestAllReduce { 8 | public static void main(String[] args) throws MPIException { 9 | // ініціалізація MPI 10 | MPI.Init(args); 11 | // визначення номера процесора 12 | int myrank = MPI.COMM_WORLD.getRank(); 13 | // визначення числа процесорів в групі 14 | int np = MPI.COMM_WORLD.getSize(); 15 | int n = 5; 16 | int[] a = new int[n]; 17 | for (int i = 0; i < n; i++) { 18 | a[i] = myrank * 10 + i; 19 | } 20 | System.out.println("myrank = " + myrank + ": a = " + Arrays.toString(a)); 21 | int[] q = new int[n]; 22 | MPI.COMM_WORLD.allReduce(a, q, n, MPI.INT, MPI.PROD); 23 | for (int j = 0; j < np; j++) { 24 | if (myrank == j) { 25 | System.out.println("myrank = " + myrank + ": q = " + Arrays.toString(q)); 26 | } 27 | } 28 | // завершення параалельної частини 29 | MPI.Finalize(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /mpj-examples/TestAllToAll.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.util.Arrays; 4 | import mpi.MPI; 5 | import mpi.MPIException; 6 | 7 | public class TestAllToAll { 8 | public static void main(String[] args) throws MPIException { 9 | MPI.Init(args); 10 | int myrank = MPI.COMM_WORLD.getRank(); 11 | int np = MPI.COMM_WORLD.getSize(); 12 | int n = 4; 13 | int[] a = new int[n]; 14 | for (int i = 0; i < n; i++) a[i] = myrank * 10 + i; 15 | System.out.println("myrank = " + myrank + ": a = " + Arrays.toString(a)); 16 | int[] q = new int[n]; 17 | MPI.COMM_WORLD.allToAll(a, 1, MPI.INT, q, 1, MPI.INT); 18 | System.out.println("myrank = " + myrank + ": q = " + Arrays.toString(q)); 19 | MPI.Finalize(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /mpj-examples/TestAllToAllv.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.util.Arrays; 4 | import mpi.MPI; 5 | import mpi.MPIException; 6 | 7 | /* 8 | mpirun --hostfile /home/andriy/hostfile -np 1 java -cp /home/andriy/mpi-dap/target/classes com/mathpar/NAUKMA/course4/Ivaskevich/TestAllToAllv 2 9 | */ 10 | 11 | /* 12 | Output: 13 | myrank = 0; 0 14 | myrank = 0; 1 15 | */ 16 | public class TestAllToAllv { 17 | public static void main(String[] args) throws MPIException { 18 | // ініціалізація MPI 19 | MPI.Init(args); 20 | // визначення номера процесора 21 | int myrank = MPI.COMM_WORLD.getRank(); 22 | int n = 4; 23 | Integer[] a = new Integer[n]; 24 | for (int i = 0; i < n; i++) { 25 | a[i] = myrank * 10 + i; 26 | } 27 | System.out.println("myrank = " + myrank + ": a = " + Arrays.toString(a)); 28 | Integer[] q = new Integer[n]; 29 | MPI.COMM_WORLD.allToAllv( 30 | a, 31 | new int[] {1, 1, 1, 1}, 32 | new int[] {0, 1, 2, 3}, 33 | MPI.INT, 34 | q, 35 | new int[] {1, 1, 1, 1}, 36 | new int[] {3, 2, 1, 0}, 37 | MPI.INT); 38 | 39 | System.out.println("myrank = " + myrank + ": q = " + Arrays.toString(q)); 40 | 41 | // завершення паралельної частини 42 | MPI.Finalize(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /mpj-examples/TestBcast.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.util.Arrays; 4 | import mpi.MPI; 5 | import mpi.MPIException; 6 | 7 | /** 8 | * Процесор з номером 0 пересилає масив чисел іншим процесорам, використовуючи роздачу за бінарним 9 | * деревом. 10 | */ 11 | public class TestBcast { 12 | public static void main(String[] args) throws MPIException { 13 | // ініціалізація MPI 14 | MPI.Init(args); 15 | // визначення номера процесора 16 | int myrank = MPI.COMM_WORLD.getRank(); 17 | int n = 5; 18 | int[] a = new int[n]; 19 | if (myrank == 0) { 20 | for (int i = 0; i < n; i++) { 21 | a[i] = myrank * 10 + i; 22 | } 23 | System.out.println("myrank = " + myrank + " : a = " + Arrays.toString(a)); 24 | } 25 | // передача даних від 0 процесора іншим 26 | MPI.COMM_WORLD.bcast(a, a.length, MPI.INT, 0); 27 | if (myrank != 0) { 28 | System.out.println("myrank = " + myrank + " : a = " + Arrays.toString(a)); 29 | } 30 | // завершення параленьої частини 31 | MPI.Finalize(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /mpj-examples/TestCreateIntracomm.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import mpi.Intracomm; 6 | import mpi.MPI; 7 | import mpi.MPIException; 8 | 9 | public class TestCreateIntracomm { 10 | public static void main(String[] args) throws MPIException { 11 | MPI.Init(args); 12 | int myrank = MPI.COMM_WORLD.getRank(); 13 | ArrayList s = new ArrayList(); 14 | s.add(0); 15 | s.add(1); 16 | s.add(2); 17 | ArrayList s1 = new ArrayList(); 18 | s1.add(3); 19 | s1.add(4); 20 | mpi.Group g = MPI.COMM_WORLD.getGroup().incl(new int[] {0, 1, 2}); 21 | mpi.Group g2 = MPI.COMM_WORLD.getGroup().incl(new int[] {3, 4}); 22 | Intracomm COMM_NEW = MPI.COMM_WORLD.create(g); 23 | Intracomm COMM_NEW_1 = MPI.COMM_WORLD.create(g2); 24 | int n = 5; 25 | int[] a = new int[n]; 26 | if (myrank == 0 || myrank == 3) { 27 | for (int i = 0; i < n; i++) { 28 | a[i] = myrank * 10 + i; 29 | } 30 | System.out.println("myrank = " + myrank + ": a = " + Arrays.toString(a)); 31 | } 32 | if (s.contains(myrank)) COMM_NEW.bcast(a, a.length, MPI.INT, 0); 33 | if (s1.contains(myrank)) COMM_NEW_1.bcast(a, a.length, MPI.INT, 0); 34 | if (myrank != 0 && myrank != 3) 35 | System.out.println("myrank = " + myrank + ": a = " + Arrays.toString(a)); 36 | MPI.Finalize(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /mpj-examples/TestGather.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.util.Arrays; 4 | import mpi.MPI; 5 | 6 | public class TestGather { 7 | public static void main(String[] args) throws Exception { 8 | // ініціалізація MPI 9 | MPI.Init(args); 10 | // визначення номера процесора 11 | int myrank = MPI.COMM_WORLD.getRank(); 12 | // визначення числа процесорів в групі 13 | int np = MPI.COMM_WORLD.getSize(); 14 | int n = 5; 15 | int[] a = new int[n]; 16 | for (int i = 0; i < n; i++) a[i] = myrank * 10 + i; 17 | System.out.println("myrank = " + myrank + " : a = " + Arrays.toString(a)); 18 | int[] q = new int[n * np]; 19 | MPI.COMM_WORLD.gather(a, n, MPI.INT, q, n, MPI.INT, np - 1); 20 | if (myrank == np - 1) { 21 | System.out.println("myrank = " + myrank + " : q = " + Arrays.toString(q)); 22 | } 23 | // завершення параленьої частини 24 | MPI.Finalize(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /mpj-examples/TestGatherv.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.util.Arrays; 4 | import mpi.MPI; 5 | import mpi.MPIException; 6 | 7 | /* 8 | mpirun --hostfile /home/andriy/hostfile -np 2 java -cp /home/andriy/mpi-dap/target/classes com/mathpar/NAUKMA/course4/Ivaskevich/TestGatherv 10 9 | */ 10 | 11 | /* 12 | Output: 13 | 0 14 | 0 15 | 1 16 | 1 17 | 1 18 | 1 19 | 1 20 | 1 21 | 1 22 | 1 23 | 1 24 | 1 25 | 0 26 | 0 27 | 0 28 | 0 29 | 0 30 | 0 31 | 0 32 | 0 33 | */ 34 | public class TestGatherv { 35 | public static void main(String[] args) throws MPIException { 36 | // ініціалізація MPI 37 | MPI.Init(args); 38 | // визначення номера процесора 39 | int myrank = MPI.COMM_WORLD.getRank(); 40 | // визначення числа процесорів в групі 41 | int np = MPI.COMM_WORLD.getSize(); 42 | int n = 5; 43 | int[] a = new int[n]; 44 | for (int i = 0; i < n; i++) { 45 | a[i] = myrank * 10 + i; 46 | } 47 | System.out.println("myrank = " + myrank + ": a = " + Arrays.toString(a)); 48 | int[] q = new int[n * np]; 49 | MPI.COMM_WORLD.gatherv(a, n, MPI.INT, q, new int[] {n, n}, new int[] {0, 5}, MPI.INT, np - 1); 50 | 51 | if (myrank == np - 1) { 52 | System.out.println("myrank = " + myrank + ": q = " + Arrays.toString(q)); 53 | } 54 | // завершення паралельної частини 55 | MPI.Finalize(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /mpj-examples/TestISendAndIRecv.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.nio.IntBuffer; 4 | import java.util.Random; 5 | import mpi.MPI; 6 | import mpi.MPIException; 7 | 8 | public class TestISendAndIRecv { 9 | public static void main(String[] args) throws MPIException { 10 | 11 | MPI.Init(args); 12 | 13 | int myrank = MPI.COMM_WORLD.getRank(); 14 | 15 | int np = MPI.COMM_WORLD.getSize(); 16 | 17 | int n = 5; 18 | 19 | IntBuffer b = MPI.newIntBuffer(n); 20 | 21 | if (myrank == 0) { 22 | for (int i = 0; i < n; i++) { 23 | b.put(new Random().nextInt(10)); 24 | } 25 | for (int i = 1; i < np; i++) { 26 | MPI.COMM_WORLD.iSend(b, b.capacity(), MPI.INT, i, 3000); 27 | } 28 | System.out.println("proc num = " + myrank + " array sent"); 29 | 30 | } else { 31 | MPI.COMM_WORLD.recv(b, b.capacity(), MPI.INT, 0, 3000); 32 | System.out.println("proc num = " + myrank + " array received"); 33 | } 34 | MPI.Finalize(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /mpj-examples/TestProbe.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import mpi.MPI; 4 | import mpi.MPIException; 5 | import mpi.Status; 6 | 7 | public class TestProbe { 8 | public static void main(String[] args) throws MPIException, InterruptedException { 9 | MPI.Init(args); 10 | int n = 5; 11 | int rank = MPI.COMM_WORLD.getRank(); 12 | int size = MPI.COMM_WORLD.getSize(); 13 | if (rank == 0) { 14 | int[] array = new int[n]; 15 | for (int i = 1; i < size; i++) { 16 | MPI.COMM_WORLD.send(array, n, MPI.INT, i, 1); 17 | System.out.println("rank = " + rank + " відправлено до " + i); 18 | } 19 | } else { 20 | Status st = null; 21 | while (st == null) { 22 | st = MPI.COMM_WORLD.probe(0, 1); 23 | } 24 | System.out.println("st.getCount(MPI.INT) = " + st.getCount(MPI.INT)); 25 | System.out.println("st.getTag() = " + st.getTag()); 26 | System.out.println("st.getSource() = " + st.getSource()); 27 | int[] array = new int[n]; 28 | MPI.COMM_WORLD.recv(array, n, MPI.INT, 0, 1); 29 | System.out.println("rank = " + rank + " отримано"); 30 | } 31 | MPI.Finalize(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /mpj-examples/TestReduce.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.util.Arrays; 4 | import mpi.MPI; 5 | import mpi.MPIException; 6 | 7 | public class TestReduce { 8 | public static void main(String[] args) throws MPIException { 9 | // ініціалізація MPI 10 | MPI.Init(args); 11 | // визначення номера процесора 12 | int myrank = MPI.COMM_WORLD.getRank(); 13 | int n = 5; 14 | int[] a = new int[n]; 15 | for (int i = 0; i < n; i++) { 16 | a[i] = myrank * 10 + i; 17 | } 18 | System.out.println("myrank = " + myrank + ": a = " + Arrays.toString(a)); 19 | int[] q = new int[n]; 20 | MPI.COMM_WORLD.reduce(a, q, n, MPI.INT, MPI.SUM, 0); 21 | if (myrank == 0) System.out.println("myrank = " + myrank + ": q = " + Arrays.toString(q)); 22 | // завершення паралельної частини 23 | MPI.Finalize(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /mpj-examples/TestReduceScatter.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.util.Arrays; 4 | import mpi.MPI; 5 | import mpi.MPIException; 6 | 7 | public class TestReduceScatter { 8 | public static void main(String[] args) throws MPIException { 9 | // ініціалізація MPI 10 | MPI.Init(args); 11 | // визначення номера процесора 12 | int myrank = MPI.COMM_WORLD.getRank(); 13 | int n = 10; 14 | int[] a = new int[n]; 15 | for (int i = 0; i < n; i++) { 16 | a[i] = myrank * 10 + i; 17 | } 18 | System.out.println("myrank = " + myrank + ": a = " + Arrays.toString(a)); 19 | int[] q = new int[n]; 20 | MPI.COMM_WORLD.reduceScatter(a, q, new int[] {1, 2, 3, 4}, MPI.INT, MPI.SUM); 21 | 22 | // if (myrank == 0) { 23 | System.out.println("myrank = " + myrank + ": q = " + Arrays.toString(q)); 24 | // } 25 | // завершення паралельної частини 26 | MPI.Finalize(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /mpj-examples/TestScan.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.util.Arrays; 4 | import mpi.MPI; 5 | import mpi.MPIException; 6 | 7 | public class TestScan { 8 | public static void main(String[] args) throws MPIException { 9 | // ініціалізація MPI 10 | MPI.Init(args); 11 | // визначення номера процесора 12 | int myrank = MPI.COMM_WORLD.getRank(); 13 | // визначення числа процесорів в групі 14 | int np = MPI.COMM_WORLD.getSize(); 15 | int n = 5; 16 | int[] a = new int[n]; 17 | for (int i = 0; i < n; i++) { 18 | a[i] = myrank * 10 + i; 19 | } 20 | System.out.println("myrank = " + myrank + ": a = " + Arrays.toString(a)); 21 | int[] q = new int[n]; 22 | MPI.COMM_WORLD.scan(a, q, n, MPI.INT, MPI.SUM); 23 | for (int j = 0; j < np; j++) { 24 | if (myrank == j) { 25 | System.out.println("myrank = " + myrank + ": q = " + Arrays.toString(q)); 26 | } 27 | } 28 | // завершення параельної частини 29 | MPI.Finalize(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /mpj-examples/TestScatter.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.util.Arrays; 4 | import mpi.MPI; 5 | import mpi.MPIException; 6 | 7 | public class TestScatter { 8 | public static void main(String[] args) throws MPIException { 9 | // ініціалізація MPI 10 | MPI.Init(args); 11 | // визначення номера процесора 12 | int myrank = MPI.COMM_WORLD.getRank(); 13 | // визначенння числа процесорів в групі 14 | int np = MPI.COMM_WORLD.getSize(); 15 | int n = 6; 16 | // оголошуємо масив об'єктів 17 | int[] a = new int[n]; 18 | // заповнюємо цей масив на нульовому процесорі 19 | if (myrank == 0) { 20 | for (int i = 0; i < n; i++) { 21 | a[i] = i; 22 | } 23 | System.out.println("myrank = " + myrank + ": a = " + Arrays.toString(a)); 24 | } 25 | // оголошуємо масив, в який будуть записуватись 26 | // прийняті процесором елементи 27 | int[] q = new int[n / 2]; 28 | MPI.COMM_WORLD.scatter(a, 3, MPI.INT, q, n / 2, MPI.INT, 0); 29 | // роздруковуємо отримані масиви і номера процесорів 30 | System.out.println("myrank = " + myrank + ": q = " + Arrays.toString(q)); 31 | 32 | // завершення паралельної частини 33 | MPI.Finalize(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /mpj-examples/TestScatterv.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.util.Arrays; 4 | import mpi.MPI; 5 | import mpi.MPIException; 6 | 7 | public class TestScatterv { 8 | public static void main(String[] args) throws MPIException { 9 | 10 | // ініціалізація MPI 11 | MPI.Init(args); 12 | // визначення номера процесора 13 | int myrank = MPI.COMM_WORLD.getRank(); 14 | int n = 4; 15 | // визначення числа процесорів в групі 16 | int np = MPI.COMM_WORLD.getSize(); 17 | // оголошуємо масив цілих чисел 18 | int[] a = new int[n * np]; 19 | if (myrank == 0) { 20 | for (int i = 0; i < a.length; i++) a[i] = myrank * 10 + i; 21 | System.out.println("myrank = " + myrank + ": a = " + Arrays.toString(a)); 22 | } 23 | // оголошуємо масив, в який будуть записуватися 24 | // прийняті процесором елементи 25 | int[] q = new int[n]; 26 | MPI.COMM_WORLD.scatterv( 27 | a, new int[] {n, n, n, n}, new int[] {0, 8, 4, 12}, MPI.INT, q, n, MPI.INT, 0); 28 | // роздруковуємо отримані масиви і номера процесорів 29 | System.out.println("myrank = " + myrank + ": q = " + Arrays.toString(q)); 30 | // завершення паралельної частини 31 | MPI.Finalize(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /mpj-examples/TestSendAndRecv.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.util.Random; 4 | import mpi.*; 5 | 6 | public class TestSendAndRecv { 7 | public static void main(String[] args) throws MPIException { 8 | // iнiцiалiзацiя MPI 9 | MPI.Init(args); 10 | // визначення номера процесора 11 | int myrank = MPI.COMM_WORLD.getRank(); 12 | // визначення кiлькостi процесорiв у групi 13 | int np = MPI.COMM_WORLD.getSize(); 14 | // вхiдний параметр - розмiр масиву 15 | int n = 5; 16 | double[] a = new double[n]; 17 | // синхронiзацiя процесорiв 18 | // MPI.COMM_WORLD.barrier(); 19 | // якщо процесор з номером 0 20 | if (myrank == 0) { 21 | for (int i = 0; i < n; i++) { 22 | a[i] = (new Random()).nextDouble(); 23 | System.out.println("a[" + i + "]= " + a[i]); 24 | } 25 | // передання 0-процесором елементiв усiм iншим процесорам у групi 26 | for (int i = 1; i < np; i++) { 27 | MPI.COMM_WORLD.send(a, n, MPI.DOUBLE, i, 3000); 28 | } 29 | System.out.println("Proc num " + myrank + " масив вiдправлено" + "\n"); 30 | } else { 31 | // приймання i-м процесором повiдомлення вiд 32 | // процесора з номером 0 та тегом 3000. 33 | MPI.COMM_WORLD.recv(a, n, MPI.DOUBLE, 0, 3000); 34 | for (int i = 0; i < n; i++) { 35 | System.out.println("a[" + i + "]= " + a[i]); 36 | } 37 | System.out.println("Proc num " + myrank + " масив прийнято" + "\n"); 38 | } 39 | 40 | // завершення паралельної частини 41 | MPI.Finalize(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /mpj-examples/Transport.java: -------------------------------------------------------------------------------- 1 | package com.mathpar.NAUKMA.examples; 2 | 3 | import java.io.*; 4 | import java.nio.ByteBuffer; 5 | import java.util.logging.Level; 6 | import java.util.logging.Logger; 7 | import mpi.MPI; 8 | import mpi.MPIException; 9 | import mpi.Status; 10 | 11 | public class Transport { 12 | 13 | public static void sendArrayOfObjects(Object[] a, int proc, int tag) 14 | throws MPIException, IOException { 15 | for (int i = 0; i < a.length; i++) { 16 | sendObject(a[i], proc, tag + i); 17 | } 18 | } 19 | 20 | public static Object[] recvArrayOfObjects(int proc, int tag) 21 | throws MPIException, IOException, ClassNotFoundException { 22 | 23 | Object[] o = new Object[4]; 24 | for (int i = 0; i < 4; i++) { 25 | o[i] = recvObject(proc, tag + i); 26 | } 27 | return o; 28 | } 29 | 30 | public static void sendObject(Object a, int proc, int tag) throws MPIException, IOException { 31 | ByteArrayOutputStream bos = new ByteArrayOutputStream(); 32 | ObjectOutputStream oos = new ObjectOutputStream(bos); 33 | oos.writeObject(a); 34 | byte[] tmp = bos.toByteArray(); 35 | MPI.COMM_WORLD.send(tmp, tmp.length, MPI.BYTE, proc, tag); 36 | } 37 | 38 | public static Object recvObject(int proc, int tag) 39 | throws MPIException, IOException, ClassNotFoundException { 40 | 41 | Status st = MPI.COMM_WORLD.probe(proc, tag); 42 | 43 | int size = st.getCount(MPI.BYTE); 44 | 45 | byte[] tmp = new byte[size]; 46 | 47 | MPI.COMM_WORLD.recv(tmp, size, MPI.BYTE, proc, tag); 48 | Object res = null; 49 | ByteArrayInputStream bis = new ByteArrayInputStream(tmp); 50 | ObjectInputStream ois = new ObjectInputStream(bis); 51 | res = ois.readObject(); 52 | 53 | return res; 54 | } 55 | 56 | public static void sendObjects(Object[] a, int proc, int tag) throws MPIException { 57 | ByteArrayOutputStream bos = null; 58 | try { 59 | bos = new ByteArrayOutputStream(); 60 | ObjectOutputStream oos = new ObjectOutputStream(bos); 61 | for (int i = 0; i < a.length; i++) { 62 | oos.writeObject(a[i]); 63 | } 64 | bos.toByteArray(); 65 | } catch (Exception ex) { 66 | Logger.getLogger(Transport.class.getName()).log(Level.SEVERE, null, ex); 67 | } 68 | byte[] temp = bos.toByteArray(); 69 | ByteBuffer buf = MPI.newByteBuffer(temp.length); 70 | buf.put(temp); 71 | MPI.COMM_WORLD.iSend(buf, temp.length, MPI.BYTE, proc, tag); 72 | } 73 | 74 | public static Object[] recvObjects(int m, int proc, int tag) throws MPIException { 75 | Status s = MPI.COMM_WORLD.probe(proc, tag); 76 | int n = s.getCount(MPI.BYTE); 77 | byte[] arr = new byte[n]; 78 | MPI.COMM_WORLD.recv(arr, n, MPI.BYTE, proc, tag); 79 | Object[] res = new Object[m]; 80 | try { 81 | ByteArrayInputStream bis = new ByteArrayInputStream(arr); 82 | ObjectInputStream ois = new ObjectInputStream(bis); 83 | for (int i = 0; i < m; i++) { 84 | res[i] = ois.readObject(); 85 | } 86 | } catch (Exception ex) { 87 | Logger.getLogger(Transport.class.getName()).log(Level.SEVERE, null, ex); 88 | } 89 | return res; 90 | } 91 | } 92 | --------------------------------------------------------------------------------