Simple Threads – a bit more complex approach

It’s great to relax and spend time with family. To much relaxing might get boring after a while so it’s time start creating!

Before moving on with our journey, I wanted to evolve a bit more the SimpleThreadsAPI. And so I did. But I also got irresolute about where is best to place some APIs. Should I keep the basic InterruptibleRunnable interface as it is? Or shall I add some more APIs to it, which frankly, are useful?

If you haven’t read the previous article, now it’s a good time to get into the basics of Java Threads: Cancel or Pause a Thread’s execution – the basics.

There is a well defined difference as time and space is concerned between the real state of the process and the state imposed by the user. A user call to pause() the process, but the process doesn’t pause immediately. Firstly, it’s on another thread, secondly the checkInterruption() will actually pause it. So far I’ve decided to keep 2 fields, one for the state the user set, called “state”, the other for the actual state of the process called “realState”. This can be done with one field as well, but expanding the range of states the process can have.

The next issue is that I’ve added property change notifications. This is great as the user can always know when the state of the process changed, or really changed. And it also allows using other properties in subclasses. But shall I add the public methods dealing property changes in the interface, or leave them in the default abstract implementation. Obvious, they should be in the interface, but I don’t really like to make that crowded. I love it simple, but might not be enough.

In order to provide a bit more complex example then the movement of a progress bar back and forth, I did a bit of refactoring on the test class. It’s much more simple now, and I could easily extend it.

I’ve implemented another process which downloads a file from a specified url location and store it on your machine in a specified file. I used this process in the second test sample. The location of the download process is here: https://github.com/bogdanudrescu/SimpleThreadsAPI/blob/master/src/grape/simple/threads/test/DownloadProcess.java

Let’s take look at and discuss the code, thanks to our friend, archerimagine, who suggested this.

Our DownloadProcess extends from AbstractInterruptibleRunnable, which is the default implementation of the InterruptibleRunnable. Instead of run(), AbstractInterruptibleRunnable requires one abstract method to be implemented, the execute() method. So here we go:

	protected void execute() throws Exception {

Then, in this particular case – downloading a file – we need to open a url connection. As you can see, the connection object is an instance member. You’ll see soon why.

		URL url = new URL(urlToDownload);

		connection = url.openConnection();

		System.out.println("Connecting to " + urlToDownload);

		// Read the lenght of the download content.
		String contentLengthString = connection.getHeaderField("Content-Length");

		checkInterruption(); // THIS IS THE TRICK

		long contentLength = Long.parseLong(contentLengthString);

		System.out.println("Connection established!");

After obtaining the connection, we need to see how large is our file, so we read the Content-Length parameter from the header of the http response. Now, this will actually download data from the server, and we don’t know how much time will take for the server to respond. What if at this moment the user cancel the process? We’re still waiting in getHeaderField("Content-Length") call and the process won’t cancel. The solution is to override the cancel() method and to set the timeout on the connection to the minimum value – 1 mills, which will force the connection to timeout.

	public synchronized void cancel() {
		super.cancel();

		// THIS IS THE OTHER TRICK
		connection.setConnectTimeout(1);
		connection.setReadTimeout(1);
	}

Then, in case of a timeout, getHeaderField("Content-Length") will end its execution with null, and the next call is checkInterruption(). As I said, this is the trick to pause or cancel your process. It will check on the state of the process and will throw an exception to cancel it or will call wait() to pause it. In your process make regular calls to this method, leaving as less time as possible in-between calls.

Let’s move on with our download. We need now to read the input stream and to store the bytes in an output stream pointing to our file. I choose 4kb as an intermediate buffer, and I’m writing the bytes immediately in the output stream. In most of the cases this should be enough.
Then I’m doing something cool. I said that I’ve added property listeners. I’ve implemented one to track the completion percent of the process. Just calling setPercentCompleted(float percent) will fire a property change event. Of-course, you need to call that because I don’t know what are the steps of your process 😉
And at the end of each loop I’m checking again if the process should cancel or pause. Just call checkInterruption(). It’s that simple.

		// Gets the data from the input stream and puts it into the output stream.
		inputStream = connection.getInputStream();
		outputStream = new FileOutputStream(fileNameToStore);

		byte[] bytes = new byte[4096];
		int length = -1;
		long contentLengthRead = 0;

		while ((length = inputStream.read(bytes)) != -1) {

			outputStream.write(bytes, 0, length);
			outputStream.flush();

			contentLengthRead += length;

			// Set the completed percent.
			setPercentCompleted(100f * contentLengthRead / contentLength);

			checkInterruption(); // THIS IS THE TRICK
		}

There is also a method called when the process ends, no matter if it’s canceled or it terminates normally. You can override it to close connections or any other finalizers you might need to do. But all the code here needs to be fast. In our case I have to make sure the input and output streams get closed.
Make sure that no exception will leave this method. The execute() method comes with throws Exception, but this one is intentionally left without to force you to catch any problems, and to make sure you close everything correctly.

	protected void executed() {

		System.out.println("Download finished.");

		if (outputStream != null) {
			try {
				outputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

And now, this is how the process is created. We also register for the “percentCompleted” change, in order to move the progress on the progress bar.

	protected InterruptibleRunnable createProcess() {
		InterruptibleRunnable process = new DownloadProcess(urlTextField.getText(), fileTextField.getText());
		process.addPropertyChangeListener("percentCompleted", new PercentCompletedListener());
		return process;
	}

And when the play button gets hit, we only start our process on a Thread and we also register to the “realState” change to enable/disable the play/pause/stop buttons accordingly:

		process = createProcess();
		process.addPropertyChangeListener("realState", new RealStatePropertyListener());

		new Thread(process).start();

In order to pause the process I just call:

		process.pause();

And to stop it:

		process.cancel();

It’s that simple 😉

This is how the test app looks, and the code is here: https://github.com/bogdanudrescu/SimpleThreadsAPI/blob/master/src/grape/simple/threads/test/TestInterruptionDownload.java

Demo

Wish you all a happy life with lot of love!

Threads

Advertisements

Cancel or Pause a Thread’s execution – the basics.

I’ve thought about this wishing to be able to stop some processes while running on some timers, and to stop them safely and clean. For instance a process would download some large amount of data, then analyze it, maybe store it, then send some mails or notifications. Basically a complex list of things that might take more the few seconds to run, up to minutes or more.

How can you safely stop a process like this? I’m sure that even if you didn’t do it so far and think a bit you might very well find solutions.

Basically, in what I did, there is only one simple trick. The idea is to constantly call a method that will throw and exception if the status is CANCEL. In more details, implement the Runnable, implement run() as final and call from there an abstract method where the actual implementation of the process will be i.e. execute(). Then in your implementation, anyplace where you can afford to stop the execution make calls to checkInterruption(), which will throw an exception in case the process was canceled, or if paused it will do a wait() until resumed.

I found this solution as being really easy to implement and use, safely enough, clean, reusable, scalable.

You can find it here as a Java implementation: https://github.com/bogdanudrescu/SimpleThreadsAPI

The API is straight forward: https://github.com/bogdanudrescu/SimpleThreadsAPI/blob/master/src/grape/simple/threads/InterruptibleRunnable.java

public interface InterruptibleRunnable extends Runnable {

	void cancel();

	void pause();

	void resume();

	public InterruptibleRunnableState getState();

	public InterruptibleRunnableState getRealState();

	public void addPropertyChangeListener(PropertyChangeListener listener);

	public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener);

	public float getPercentCompleted();
}

https://github.com/bogdanudrescu/SimpleThreadsAPI/blob/master/src/grape/simple/threads/InterruptibleRunnableState.java

public enum InterruptibleRunnableState {

	NOT_RUNNING,

	RUNNING,

	PAUSED,

	CANCELED
}

OK, the actual code looks more beautiful, but to save some space here I remove the comments. 🙂

Quick look on the actual class implementation: https://github.com/bogdanudrescu/SimpleThreadsAPI/blob/master/src/grape/simple/threads/AbstractInterruptibleRunnable.java

It also contains a very simple test sample on how to use it.

For a bit more complex example please read the next article: Simple Threads – a bit more complex approach

I called my package grape simple because my wife really love grapes. We have the custom each year to make wine, which we froze it on the spot. We can thus open the bottles at any time and it will be really sweet and with no alcohol.

Autumn Grape

Knowing yourself

Do you know how you really are?

You’re going to work, meet your friends, colleagues. You need to show up and represent yourself. But when do you truly act as yourself? When you’re only with the closest friends? When you’re with your family? When you are alone?

Have you ever tried a monk’s life? A hermit’s life? Just for a short while maybe?

Well, being solely alone, most likely might drive you crazy. I think there are not so many people to stand for this and remain rational. The astronauts for instance train really hard on this. We are social beings, we need to interact, we need to see and feel others like us. But every now and then we should take some time to be only with ourselves. Some calls this praying. Others meditation. Others relaxation…

Let me tell you my story. Few years ago I made a switch in my job to work from home, doing what I know, software. It sounds like modern classic for me. Well, I do live in the country side at the edge of a village, and someone might say in the middle of nowhere. But actually it’s not really being alone.

Home

I live with my wife and kids, and most of the time we all stay at home, together. Always being with people I love, for whom I have nothing to hide, having almost no time in the presence of others to whom I mostly needed to make a good impression, really makes me see who I really am. Also it make me wish to communicate, and though I was a really shy person, I’m much more open to other people, and the reason I started to express myself. I figured out that only trying to impress the others it’s just being fake, obvious.

No one should be ashamed of himself. We are just different and all valuable. And being different is great! It would be really boring if we all would be the same. If someone discredit you, then he’s the one to be ashamed.

So, if you really what to know yourself, take some time alone and pay attention to yourself. Just like that!

And if you believe in God and you’re honest, you might even hear Him. It’s the sound of your heart telling you the truth.

Gheorghe Zamfir in Craiova

The best panflute musician in the world, Gheorghe Zamfir, was present today at the University of Craiova (Romania), at an event dedicated to him and the launch of the book “Gheorghe Zamfir, a Romanian wonder”. The book might not get translated to English, but it’s enough info on the internet about him, so who’s interest just google “Gheorghe Zamfir”.

I had the pleasure to hear him and listen him playing the panflute today. It was an emotional moment, especially when he is one of my favorite musician and a great artist.

Luiza Roșulescu posted a small recording from the event. My phone was with my 3 years old son to keep him quiet 🙂 so I only have few photos from the event, from the back of the audience :).

For more informations about Gheorghe Zamfir please check his web site: http://www.gheorghezamfir.ro (http://www.gheorghezamfir.ro/?page_id=3430 – english version)

I think he’s most known for performing James Last’s “The Lonely Shepherd” from the soundtrack of Quentin Tarantino’s “Kill Bill vol 1”, which is indeed a great piece of art.

For more info about him, please visit the wiki page: http://en.wikipedia.org/wiki/Gheorghe_Zamfir, and search on youtube to listen him performing: https://www.youtube.com/results?search_query=gheorghe%20zamfir

Gheorghe Zamfir

Divide et impera

We’re not at History, but I just want to make use of this to express in a funny way how can you came up with a really powerful product design.

I’m going to talk about software, because this is what I do most, but this apply to any kind of product or service development.

One of the main problem in software is that the design behind a product, usually is not so good. We tend to think that if we rush to do something because our mind think faster then we write, it’s better then just sit quite for a while and think.

This is very well expressed in the woodpecker joke:

If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. (Gerald Weinberg)

So why do you need a good design? 2 main reasons:

  1. Reusability. You don’t want to write or copy/paste the same stuff again and again.
  2. You always need a scaled design.

Scalability has 2 sides:

  1. It’s the ability to easily change the product so you can keep up with the changes in the specifications. And the specs … they always change. The initial specs won’t last to long. That’s proven.
  2. It’s the capacity of a system to handle more load, i.e. growth in the amount of users or processes it needs to handle.

Just handle first side and the second will be handled by itself with only some extra resources and maybe a bit more work. The product design is the critical aspect for a good, long term development process.

So how do you know your design is a good one? In the end we based our development on a design, good or bad, but it’s a design.

OK, most likely it’s not going to be perfect from the first time, but the more you choose the right approach, the easier will be next time and so on. And even if you start with a design that’s not so good, and you figure out in time the mistakes, trust me, you’ll end up fixing it without starting it over from the scratch. And refactoring will be like a bad dream, because now you’re in the real world.

There it one rule only (which we can divide it into sub rules, but maybe later :)), and it always work. The title :). Yes, the title! Divide et impera. It sound hilarious, but I like how it sound. It’s not really like we’re conquering anything, but we do have lots of benefits. From what? From dividing. And what’s even more funny then what I expected to be, is that this quote is around for more then 2000 years. Look for it!

Yes, this is the basic of an almost perfect design. That’s because there’s nothing perfect in this world. And we need to cope as much as possible with it.

So let’s get into a bit of details. You have a problem, which is more or less complex. Go ahead and divide it into subproblems, then the subproblems into more subproblems, and these ones as well, and so on. What you’ll end up with is a set of modules, very simple modules. Take those modules and implement them separately, and try to think at the right way to do it, taking into account any other context where you might use that particular module. You’ll end up with the first gain of doing so: reusability.

For instance, you need a circle in your calculations. Make an Ellipse class, then extend it to a Circle. You put all the properties inside and then you’re good to go. Anywhere you’ll need a circle or ellipse, you don’t need to rethink the whole stuff again. Don’t keep it with 2 members where you need it, like center and radius, or x, y, r, which are actually 3. Just use a Circle object.

Let’s say in your app you want to create an UI. Don’t do it only for the context you’re in. Maybe you’ll need to show that in another context later. You don’t have to do it twice and to copy/paste buckets of code form a place to another. Write it only once in a way so you can use it in several places.

Do not make cross references. This is a really poor approach. It will force your module to depend on to many external things, while you need it free. Use delegates or listeners instead.

Then take the modules and link them. Method calls, references, delegates, maybe some algorithms, you name it. The link it’s just an abstract bridge between the modules. A way to communicate or to keep them tie. Like a wire or a screw.

Doing this you have all the chances to end up with a great design for your app or product or whatever project you might have. You’ll have reusable components, the project will be flexible, scalable, modular, just like that, and you’ll be really happy, and really amassed that this actually works. And even the woodpecker won’t be able to crack it 😉

Art in everything

We tend to think that each of us has a predominant characteristic that influence our life, our relations, our work. When I was in school, we were split into 2 groups, one for human arts, like languages, philosophy, music and another group for science (math, physics, computer science). More or less, depending also on the culture of each region on the globe, there is a separation between the type of achievements we made. Art and science are said to be 2 distinct things.

If you look closely though, both artists and scientists produce. They make something. Artists create paintings, music, literature, movies. Engineers produce cars, aircrafts, buildings. But then, how can you paint without the combination of colors which implies maybe at least a bit of chemistry? And how can a movie maker do his job without the tools engineered to shoot images or create stunning graphic effects? Then how can a car look cool without the shapes of a designer? Or a building constructed without the design of an architect? And then there is food, which will all eat. Ask a cook, a real chef, what is food for him? Food is love, is passion, is art. And yet it’s so much more. You need fire, energy, ones of the most interesting things to be studied by scientists.

So in the end there might be a deep bond between the 2 sides of our personality.

There are also some people with great achievements who demonstrated that when the two sides join, great achievements can be made.

Chris Hadfield, commander of the ISS Expedition 35 was the most social astronaut and even brought a guitar in space and enchanted us with his Space Oddity – http://www.youtube.com/watch?v=KaOC9danxNo.

Steve Jobs, co-founder and CEO of Apple was the first to bring fonts to a text editor, just because while in school, he attended a calligraphy course which he really enjoyed it.

Not to talk about Leonardo da Vinci who covered almost all the titles, from painter, musician to engineer and inventor.

So, how is art present in software development? Isn’t computer science very precise, so precise that any interpretations or feelings are not allowed? How can a block of code be considered in the same time a real fact and a piece of art?

My first blog

You know, this is quite fun for me right now. I’m kind of a shy person, who almost never took initiatives involving others, except me.

I’m really good working with myself, and I’m trying with others as well, mostly with my wife, which is obvious, as we are the best friends. But when it comes to relate or do anything that doesn’t involves a strong or at least a good relation, I’m not very happy.

And yes, this is my first blog ever, except some photos on Facebook, where I’m stingy though. I’m asked to post more and I say, “well I can show them to you directly if you really want to see my kids”.

Most of my time, I’m building software, almost alone, home alone. Except for my wife who is with me all the time, and my 2 boys, 2 for now, I wish more, but we’ll see… I’m dreaming to reach 90 or more, together with my wife, and get surrounded by our kids and theirs and so on… you get the point.

OK, what I want to do further with this WordPress stuff is to post the things I encounter, mostly in my work. I have lots of thoughts I want to share. I’m reaching a point where I really need to do something, and because I’m a shy guy, and not so very good in speech, writing is my place to be. So I’ll try to write anything that comes across me.

Hope you’ll enjoy, and even if you don’t, well… thanks for reading anyway.

Wish you all the best and plenty of love.