Java class for visualising Graphs

Hello, everyone!
While studying graph algorithms I created a class that helps visualise what your algorithm is doing. That’s helpful for debugging and helps learn the way the algorithm works.

ezgif.com-crop
DFS algorithm in action

You can plug any graph algorithm, the important part is to notify the JPanel whenever you want to repaint.

Here is the code:


package com.algos;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.*;
public class GraphPanel extends JPanel {
private static final long serialVersionUID = 7148504528835036003L;
private List<GraphNode> graph = new ArrayList<>();
public static class GraphNode {
public static final double radius = 30;
public Point point;
public int index;
public List<GraphNode> children;
public boolean currentlyVisited = false;
public GraphNode(int index, Point point) {
this.point = point;
this.index = index;
children = new ArrayList<>();
}
public void draw(Graphics g) {
if (this.currentlyVisited) {
g.setColor(Color.GREEN);
g.fillOval(this.point.x, this.point.y, (int)radius * 2, (int)radius * 2);
} else {
g.setColor(Color.BLACK);
g.drawOval(this.point.x, this.point.y, (int)radius * 2, (int)radius * 2);
}
g.setColor(Color.BLACK);
g.drawChars(new char[]{Character.forDigit(this.index, 10)}, 0, 1, this.point.x, this.point.y);
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (GraphNode gf : graph) {
gf.draw(g);
for (GraphNode child : gf.children) {
g.drawLine(gf.point.x + (int) GraphNode.radius, gf.point.y + (int) GraphNode.radius, child.point.x + (int) GraphNode.radius, child.point.y + (int) GraphNode.radius);
}
}
}
public void addNodes(GraphNode… nodes) {
this.graph.addAll(Arrays.asList(nodes));
}
}

view raw

GraphPanel.java

hosted with ❤ by GitHub

And here is how you might use it.


package com.algos;
import com.algos.GraphPanel.GraphNode;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Point;
import java.util.ArrayDeque;
import java.util.Queue;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* A panel maintaining a picture of a Do Not Enter sign.
*/
public class GraphsGraphics {
private static boolean[] visited = new boolean[100];
private static Queue<GraphNode> queue = new ArrayDeque<>();
public static void DFS(GraphNode currentNode, GraphNode searchedNode, JPanel panel) {
System.out.println("Currently we are visiting node " + currentNode.index);
currentNode.currentlyVisited = true;
panel.updateUI();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
currentNode.currentlyVisited = false;
panel.updateUI();
if (currentNode.index == searchedNode.index) {
System.out.println("Node found: " + searchedNode.index);
return;
}
if (visited[currentNode.index]) {
return;
}
visited[currentNode.index] = true;
for (GraphNode child : currentNode.children) {
DFS(child, searchedNode, panel);
}
}
public static void BFS(GraphNode currentNode, GraphNode searchedNode, JPanel panel) {
currentNode.currentlyVisited = true;
panel.updateUI();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
currentNode.currentlyVisited = false;
panel.updateUI();
if (currentNode.index == searchedNode.index) {
System.out.println("Node found: " + searchedNode.index);
return;
}
if (visited[currentNode.index]) {
return;
}
System.out.println("Currently visiting node " + currentNode.index);
visited[currentNode.index] = true;
for (GraphNode child : currentNode.children) {
queue.add(child);
}
if (!queue.isEmpty()) {
BFS(queue.poll(), searchedNode, panel);
}
}
/**
* A little driver in case you want a stand-alone application.
*/
public static void main(String[] args) {
GraphNode rootNode = new GraphNode(0, new Point(300, 20));
GraphNode node1 = new GraphNode(1, new Point(200, 100));
GraphNode node2 = new GraphNode(2, new Point(400, 100));
GraphNode node3 = new GraphNode(3, new Point(500, 200));
GraphNode node4 = new GraphNode(4, new Point(100, 200));
GraphNode node5 = new GraphNode(5, new Point(40, 300));
GraphNode node6 = new GraphNode(6, new Point(200, 300));
rootNode.children.add(node1);
rootNode.children.add(node2);
node1.children.add(node4);
node2.children.add(node3);
node4.children.add(node5);
node4.children.add(node6);
GraphPanel panel = new GraphPanel();
panel.addNodes(rootNode, node1, node2, node3, node4, node5, node6);
SwingUtilities.invokeLater(() -> {
panel.setBackground(Color.GRAY.darker());
JFrame frame = new JFrame("A simple graphics program");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.setVisible(true);
});
BFS(rootNode, node6, panel);
}
}

view raw

Main.java

hosted with ❤ by GitHub

Happy learning!

Understanding Thread Pools in Java

Many times we use tools Java provides out of the box, but rarely do we dig deeper into how they function. As many would argue that you could be just fine and that some level of ignorance is healthy, we as software engineers have an innate urge to understand how things work.

In this post, we will build a really basic thread pool and pinpoint some drawbacks that the approach may present.

What is a thread pool?

Before getting into the code, let’s understand what is a thread pool on a higher level.

Imagine that you are manager of a fast food restaurant and you have 10 employees working for you. Usually there is 1 employee that works from the start, until the end of the working day. If there is a spike in clients, you start calling the other employees to arrive at work. After 30 minutes the employees you called came and started work. During that time there were some unhappy customers that left the restaurant because they saw things are going really slow with only one open cashier. As the incoming workers started helping things came back to normal.

After awhile, you as a manager, noticed that these spikes have a pattern and you decide to call all the people on certain days. That way people would have warmed-up before the spike hits and all customers will be served timely.

Now, for the computer world example… I think you got this…but in short – If you have only one thread working and you summon new ones ad-hoc there is time and resources wasted during the initialisation and destroy phase of the thread. If the spikes in load are not planned and happen frequently the JVM would spend a lot of time doing thread management and you would have less resources to do the actual work that you have created the program for!

If you, on the other hand, expect these spikes to happen often or you know that your load is unpredictable you could create a few threads beforehand. And these would be your thread pool!

Implementing a thread pool

Let’s see how we can implement a thread pool in Java.

First, let’s start with the way we are going to use the Thread pool, so we start on the high level, and then we will go into the implementation of each component.


public class Main {
public static void main(String[] args) throws InterruptedException {
ITask summator1 = new Summator((byte) 90);
ITask summator2 = new Summator((byte) 9);
ITask summator3 = new Summator((byte) 30);
ITask summator4 = new Summator((byte) 65);
ITask summator5 = new Summator((byte) 100);
IThreadPool myThreadPool = new ThreadPool(4, 4);
myThreadPool.schedule(summator1);
myThreadPool.schedule(summator2);
myThreadPool.schedule(summator3);
myThreadPool.schedule(summator4);
myThreadPool.schedule(summator5);
Thread.sleep(1000);
myThreadPool.stop();
}
}

view raw

Main.java

hosted with ❤ by GitHub

First we create a few tasks Summator that we feed into the thread pool. We setup the pool to have 4 threads ready to do the job and the maximum number of tasks in the buffer is 4.

Let’s take a look at the ThreadPool class.


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ThreadPool implements IThreadPool {
private List<PoolThread> threads;
private BlockingQueue<ITask> tasks;
private volatile boolean isStopped = false;
public ThreadPool(int numberOfThreads, int maxNumberOfTasks) {
threads = new ArrayList<>();
tasks = new ArrayBlockingQueue<>(maxNumberOfTasks);
this.fillThreads(numberOfThreads);
this.start();
}
@Override
public synchronized void schedule(ITask task) {
if (this.isStopped) {
throw new IllegalArgumentException("Cannot accept any more tasks!");
}
try {
this.tasks.put(task);
} catch (InterruptedException e) {
}
}
@Override
public synchronized void stop() {
this.isStopped = true;
for (PoolThread thread : this.threads) {
thread.interrupt();
}
}
private void start() {
for (Thread thread : this.threads) {
thread.start();
}
}
private void fillThreads(int numberOfThreads) {
for (int i = 0; i < numberOfThreads; i++) {
this.threads.add(new PoolThread(this.tasks));
}
}
}

view raw

ThreadPool.java

hosted with ❤ by GitHub

Pay no attention to the IThreadPool interface which I used just to design the API of the class.

In the constructor we initialise a Blocking Queue with the parameter that denotes the maximum number of tasks that you can add to the queue before the producer has to wait to add additional item.

We also initialise a list of PoolThread which is just extends Thread and waits for tasks from the queue.

The schedule method adds a task to the queue.

The stop method interrupts all threads.


import java.util.concurrent.BlockingQueue;
public class PoolThread extends Thread {
private BlockingQueue<ITask> tasks;
private boolean isStopped = false;
public PoolThread(BlockingQueue<ITask> tasks) {
this.tasks = tasks;
}
@Override
public void run() {
while (!this.isStopped) {
try {
ITask task = this.tasks.take();
task.workOnTask();
} catch (InterruptedException e) {
this.isStopped = true;
}
}
}
}

view raw

PoolThread.java

hosted with ❤ by GitHub

PoolThread is the worker, the individual employee that can perform a task. So in our case this worker just calls a method on the task, effectively starting it. In the restaurant example that would mean switching on the oven.

run method waits for tasks on the queue. the take call will block until a task is added to the queue. BlockingQueue is interesting by itself, so I would encourage you to check this article if you want to know more.

The final piece is the class that I use as a unit of work is Summator class. I used a custom interface but you can use Runnable too.


public class Summator implements ITask {
private byte endRange;
private long result;
public Summator(byte endRange) {
this.endRange = endRange;
this.result = 0;
}
@Override
public void workOnTask() {
for (int i = 1; i < this.endRange; i++) {
this.result += i;
}
String msg = "Done with the task! The result is: " +
this.result +
"; The job was done from thread: " +
Thread.currentThread();
System.out.println(msg);
}
}

view raw

Summator.java

hosted with ❤ by GitHub

You can implement the Task interface and make other tasks that our ThreadPool can work with.

Risks

  • Deadlock – this can happen when a async task can wait on another async task. What can happen is that “Task 1” can wait on “Task 2” and vice versa. The program cannot continue.
  • Thread leakage – When a thread is taken from the pool but is not returned to it. If that thread throws exception that will reduce the size of the pool. Eventually leading to empty thread pool.
  • Thread starvation – when there are too many threads, some of them will not get tasks. Also, having many threads increases the context switching between them.

Considerations

It is important to properly calculate the size of the pool. It is a general rule of thumb to have as many threads as there are cores in your processor + 1. But we have to keep in mind that the threads could wait on I/O.

Summary

I hope that after this article you have a better understanding how thread pools work and it should make you more confident about using, configuring and tuning your thread pool!

Java has wonderful classes that abstract the thread pool for you, so I would advice you to use them! Have some fun with Java Executor!

Happy coding!

Change page title and then send event to Google Analytics – Angular 2+

When you integrate Google Analytics in your single page application and you already have a custom browser titles (the title​ in `head` tag) on every page you may have experience a pretty major issue – Google analytics event is sent before Angular was able to update the title. As a result, in Google Analytics dashboard you get the pageview associated with the previous page title.

How can we solve this problem?

It’s not a real issue but it took me some time to figure it out. The solution has to do with how observables work. Subscribers callbacks will be executed in the order in which they have subscribed. So for example, if I subscribed for a magazine and Bob also subscribed for the same magazine, in RxJS world I would get the event that the new series is out first and Bob will receive the news later, after me.

So the solution is to first subscribe and set the page title and then do the subscription to send event to Google analytics! So in your code the order should be organised so, that the subscription code of the logic that changes the page title should be before the subscription code that sends event to google analytics.

Note: If you haven’t implemented dynamic page titles yet, head to this amazing article.

Say we have the following code in app.component.ts

Here we are doing the magic explained in the article above and changing the page title.

Screenshot 2019-04-02 at 18.28.29Here we are subscribing to navigation and send the url to google analytics.

Screenshot 2019-04-02 at 18.25.32

Alright, so both subscriptions are for router.events and each of them needs different event object.

Another solution, if you do not want to refactor the order in which code is executed is to use delay(0) inside the pipe method before the subscription you want to come second.

Hope that was helpful!

Think before and after you DO!

I make a lot of mistakes…at work, outside of work, everywhere I go!

So usually after a major failure I stop, cry and think of what caused the mishap. What made me make that decision…So I made a list with the most common causes:

  • Nervousness/Anxiety/Being stressed out
    • Example: Booking a ticket after a fight with your close ones.
  • Pressure to act/respond quickly
    • Manager approaches you and asks you if you can finish something, he is in a hurry, the deadline is approaching, you just say “Sure, boss!”
  • False assumptions/prejudice, lack of knowledge
    • You always thought that changing a name on a flight ticket is easy-peazy so you do not double check nothin’.
  • Not focused, distracted by something else
    • Writing code while listening to other team’s conversation happening in the same room

So I compiled a list of reminders that could be helpful to reduce these:

  • Never do anything when anxious or really stressed, leave it for later! 🙂
  • Stay calm and think about the whole picture, the consequences, only then respond. People might think that you turned into a vegetable for a minute there, but you’ll save yourself problems and will build trust.
  • Just read more and when you think you know something spend another 5-10 minutes to read about it. You will learn extra and you will build confidence.
  • Time-boxing is a great technique to stay focused on a task. You still wont miss chatting to your friends or booking a vacation with your loved one and you will get a lot more work done!
  • Take breaks regularly. That helps seeing the bigger picture.

In conclusion, I might say that, especially in software development things should be really well thought out, do not rush through things just to get them done. That wont benefit your career because you wont develop deep knowledge and wont benefit your life in general.

Good luck!

Spring – How to store uploaded file on the server

A common task that might pop-up (hopefully just once and then abstract) in the life of a software engineer is to handle a file upload from the client and store it in a folder on the server machine.

 

If you are using Spring that can be done really easy, even easier if you are willing to add some third party libraries in your project that would make writing the file on the server easier and more terse.

Let’s check our Controller, or in other words, the method that is called when a request comes to the server for specific URL + HTTP METHOD combination.

@RequestMapping(
    path = "/process",
    method = RequestMethod.POST,
    consumes={"multipart/form-data"},
    produces= {"application/zip"}
)
public FileSystemResource process(@RequestParam("file_upload") MultipartFile file, HttpServletResponse response) {

The important parts here are the “consumes” property. The value is a specific Mime Type which is a great format for uploading files or binary data. Which basically means “Hey, I eat only sliced bread”. This format specifies a boundary, or a term that is more familiar, a separator for each of the fields in the form, so we get something like a map at the end and we need to get the file. The way that we tell Spring that we want a specific value from this map is with the @RequestParam annotation.

Where this map comes from originally?

On the client we construct it. For that, we use the FormData class.

An example of a function that encodes an uploaded file (that which comes from the input with type=””file”) to FormData:

public fileToObjectData(file: File) {
  let formData: FormData = new FormData();

  formData.append('file_upload', file, file.name);

  return formData;
}

We use the key “file_upload” so at the other end, on the server we use the same key to fetch the File (not really a file, as you will learn soon…)

As we can see from above, the type of the file is MultipartFile. In order to save it on the file system we need to convert it to the Java’s File class.

public File convert(MultipartFile multipartFile) throws IOException { 
  File convFile = new File(buildFilePathName(multipartFile));
  convFile.createNewFile(); 
  FileOutputStream fos = new FileOutputStream(convFile); 
  fos.write(multipartFile.getBytes());
  fos.close(); 
  return convFile;
}

Let’s go through the lines one by one.

1. A “magic” method that takes the filename and appends in on the output folder path to create File’s path.
2. We create empty file on the file system, only if it does not exist yet.
3. Create a FileOutputStream in order to write to the file we created.
4. Write the byte data from the MultipartFile instance.
5. Closing the resource so it’s free to use by other threads and to free the references.
6. You know that one…

And that’s it!

Factorization of a number in C

Let’s see how we can split a real number into prime numbers.

One of the main theorems in mathematics states that every real number R (R > 1) can be represented with prime numbers P1, P2, P3 where (P1 < P2 < P3.. etc.)

So for example:

  • 520 = 2 * 2 * 2 * 5 * 13
  • 64 = 2 * 2 * 2 * 2 * 2 * 2
  • 2345 = 5 * 7 * 67

How we can do that in C:

1. Include the library needed for in/output to the console.


#include stdio.h

2. Next we declare the number which we want to factorize


unsigned n = 432;

3. We should have a variable that is the current factor. We start from 1, but in the beginning of the “while” we increment, so effectively we are starting from 2.


unsigned i = 1;

4. We declare the body of the main (outer) loop. It will process until the number we are factorizing is different from 1.


while (n != 1) {
....
}

5. First step in the loop is to increment “i” which will lead us to the next factor.
Note: this code is in the main “while” loop described above.


i++;

6. We need a variable to count the number of times the current factor is contained in “n”.


unsigned k = 0;

7. We start another (inner) “while” loop that will divide “n” by “i” until it cannot be evenly divided.


while (n % i == 0) {
....
}

8. In the above (inner) “while” loop we increment “k” (the number of times a factor exists in the number we want to factorize – “n”). And we also reduce “n”, by dividing it with “i”.


k++;
n /= i;

9. Next we print the current factor “i”, “k” number of times.


for (j = 0; j < k; j++) {
printf("%u ", i);
}

That’s it! As console output we get all the factors, starting from the smallest.

Hope you enjoyed this lesson, if you did, please subscribe for more!