Java Multithreading – Executor Example

Java Multithreading – Synchronized Methods and Synchronized Code Blocks

You make a method synchronized when you want to acces it by only one thread at a time.

Look at this example:

The output should be one million, right? Try it… it works? Well try again. It works not every time, becase the addOne() method can be accesed by by the two threads.
To make it threadsafe and make it work every time (so you are getting the expected output on every run) you have to make the method synchronized.

The fixed code:

Only the fixed method:

Synchronized Code Blocks

When you are using synchronized methods (like in the example) you are using the lock of the Starter object. When you to let more threads do some work in the same time you have to create a mock object on which you synchronize.

An quick change on the addOne() will do the trick:

Java Multithreading – Thread sleep(), yield() and join() methods

To understande how this methods work you have to know which of them are static methods and wich are instance methods

Static Thread class methods

  • sleep()
  • yield()

Instance Thread class method

  • join()

sleep()

The sleep() method causes the currently executing thread to sleep for X milliseconds.
An example for sleeping for 2 seconds (2000 milliseconds).

yield()

Currently running thread goes back to its runnable state (so it’s ready to run again, but is currently not running), so other threads have a chance to run. It’s only a hint for the thread scheduler (it can be ignored), so the given behavior (goin back to runnable state) is not guaranteed.

join

This instance method causes the currently running thread to join the end of the thread “t”. You will get it after this example…

An example:

The output is:

Without the t.join() the output would be:

Java Multithreading – the volatile keyword

By adding the volatile keyword to a variable you are telling the compiler that the variable’s value will be modified by different threads.

A Simple example

Java Multithreading – starting a new thread

There are a few ways to start a new Threat in Java.

Extending the Thread class

It’s important to use the start() method and not the run() method. By using the run() method on the SomeThread class the code from run() is executed in the main thread (not in a separate thread).

Implementing the Runnable interface

You can implement the Runnable interface and pass a new instance of the class to a Thread constructor.

The quick way with Runnable interface implementation

This is a shortcut for the Runnable implementation version.

Another important thing to remember. The start() method can only be called once on an object. When you call it a second time you get a java.lang.IllegalThreadStateException.

Protocol Buffers (Protobuf) – Java Example

Protobuf is a cross-platform technology developed by Google for data serialization. It can be used as a more efficient alternative for XML and JSON. You can find a C++, Java and Python tutorial on Google’s website. Let’s write a simpler example in Java – saving an object to a file / reading from a file.

First things first…

You have to define how you want to structure your data. This is done in a .proto file.
The following example can be used for a Cat object with two fields: age and name.

The example is pretty self-explanatory. The only strange thing are the tag numbers. They are used for the order of the messages in the binary reprezentation of the object. For more details check the Protocol Buffers Language Guide.

From this proto message the proto compiler creates a class. The name of the generated Java class is defined with option java_outer_classname. The classname can’t be the same as the message or you will get the following error message:

Cannot generate Java output because the file’s outer class name, (…) matches the name of one of the types declared inside it. Please either rename the type or use the java_outer_classname option to specify a different outer class name for the .proto file.

How to install the protoc compiler?

On Mac / Ubuntu:
Download the source from here.
./configure
make
make check
sudo make install

Windows:
Download the compiler from here.
Then you can use it like that:

To simply use protoc place the binary in your PATH.

Maven Dependncy / JAR

To use protos in your project you have to add the jar in your buildpath or use a Maven dependncy:

Some of the important methods from the generated class

  • byte[] toByteArray()
  • parseFrom()
  • writeTo(OutputStream)
  • parseFrom(InputStream)
  • isInitialized()
  • toString()
  • mergeFrom(…)

Simple Example – saving an object to a file / reading from a file

Let’s create a cat object, serialize it to the cat.ser file and read it later