Anda di halaman 1dari 166



POUL KLAUSEN

JAVA 8: MULTITHREADED
PROGRAMS
SOFTWARE DEVELOPMENT

2
Java 8: Multithreaded programs: Software Development
1st edition
© 2017 Poul Klausen & bookboon.com
ISBN 978-87-403-1820-3
Peer review by Ove Thomsen, EA Dania

3
JAVA 8:MULTITHREADED PROGRAMS Contents

CONTENTS
1 Foreword 6

1 Introduction 8
1.1 Create a thread 8
1.2 Threads properties 12
Exercise 1 16

2 join 17
Exercise 2 19

3 Synchronization of threads 21
Exercise 3 28

4 Deadlock 30

5 Stop a thread 32

6 wait() and notify() 34


Exercise 4 37
Exercise 5 38

Free eBook on
Learning & Development
By the Chief Learning Officer of McKinsey

Download Now

4
JAVA 8:MULTITHREADED PROGRAMS Contents

7 Timers 39
Problem 1 43

8 Concurrency Tools 47
8.1 Executors 47
Exercise 6 51
8.2 CountDownLatch 52
Exercise 7 56
8.3 CyclicBarrier 56
Problem 2 61
8.4 Exchanger 62
8.5 Semaphore 65
Exercise 8 70
8.6 Phaser 74
8.7 Locks 79
Exercise 9 85
8.8 ReadWriteLock 85
Exercise 10 88
8.9 Collections 88
Exercise 11 92
8.10 Parallelism 95
Exercise 12 102
8.11 CompletionService 103

9 Atomic variabler 105

10 Swing 107
10.1 SwingWorker 116
10.2 A Timer 119

11 Calendar 123
11.1 Task formulation 123
11.2 Analysis 123
11.3 Design 128
11.4 Programmering 138
11.5 Test 160
11.6 Delivery 160

Appendix A 161
JVM implementations 163
The runtime system 163

5
JAVA 8:MULTITHREADED PROGRAMS Foreword

1 FOREWORD
This book is the eighth in a series of books on software development. The programming
language is Java, and the language and its syntax and semantics fills obviously much, but
the books have also largely focus on the process and how to develop good and robust
applications. This book deals with threads, and how you in Java can synchronize threads
that share resources. The use of threads is an important issue in programming, but it is
also a technical area to which are attached many details. The book has therefore primarily
focus on programming and the language Java, and only in the final example, there is again
focusing on system development and thus the process. After reading the book the reader
should be able to use threads in practice and have an understanding of where threads can
be used in practical programming. The book requires knowledge of programming and Java
corresponding to the content of the first four books in this series and in the interests of the
final example is also assumed knowledge of the contents of the previous book, which deals
with system development. The book ends with an appendix that gives a general introduction
to the Java virtual machine JVM and what it is.

As the title says this series of books deals with software development, and the goal is to
teach the reader how to develop applications in Java. It can be learned by reading about
the subject and by studying complete sample programs, but most importantly by yourself
to do it and write your own programs from scratch. Therefore, an important part of the
books is exercises and problems, where the reader has to write programs that correspond to
the substance being treated in the books. All books in the series is built around the same
skeleton and will consist of text and examples and exercises and problems that are placed
in the text where they naturally belongs. The difference between exercises and problems is
that the exercises largely deals with repetitions of the substance that is presented in the text,
and furthermore it is relatively accurately described what to do. Problems are in turn more
loosely described, and are typically a little bigger and there is rarely any clear best solution.
These are books to be read from start to finish, but the many code examples, including
exercises and problems plays a central role, and it is important that the reader predict in
detail studying the code to the many examples and also solves the exercises and problems
or possibly just studying the recommended solutions.

All books ends with one or two larger sample programs, which focus primarily is on process
and an explanation of how the program is written. On the other hand appears the code only
to a limited extent – if at all – and the reader should instead study the finished program
code perhaps while testing the program. In addition to show the development of programs
that are larger than the examples, which otherwise is presented, the aim of the concluding
examples also is to show program examples from varying fields of application.

6
JAVA 8:MULTITHREADED PROGRAMS Foreword

Most books also ends with an appendix dealing with a subject that would not be treated
in the books. It may be issues on the installation of software or other topics in computer
technology, which are not about software development, but where it is necessary to have
an introductory knowledge. If the reader already is familiar with the subject, the current
appendix can be skipped.

The programming language is, as mentioned Java, and besides the books use the following
products:

-- NetBeans as IDE for application development


-- MySQL to the extent there is a need for a database server (from the book Java 6 onwards)
-- GlassFish as a web server and application server (from the book Java 11 onwards)

It is products that are free of charge and free to install, and there is even talk about products,
where the installation is progressing all by itself and without major efforts and challenges.
In addition, there are on the web detailed installation instructions for all the three products.
The products are available on Windows and Linux, and it therefore plays no special role if
you use Linux or Windows.

All sample programs are developed and tested on machines running Linux. In fact, it plays
no major role, as both Java and other products work in exactly the same way whether the
platform is one or the other. Some places will be in the books where you could see that
the platform is Linux, and this applies primarily commands that concerning the file system.
Otherwise it has no meaning to the reader that the programs are developed on a Linux
machine, and they can immediately also run under Windows unless a program refers to
the file system where it may be necessary to change the name of a file.

Finally a little about what the books are not. It is not “how to write” or for that matter
reference manuals in Java, but it is as the title says books on software development. It is
my hope that the reader when reading the books and through the many examples can find
inspiration for how to write good programs, but also can be used as a source collection
with a number of examples of solutions to concrete everyday programming problems that
you regularly face as a software developer.

7
JAVA 8:MULTITHREADED PROGRAMS IntroduCtIon
JAVA 8:MULTITHREADED PROGRAMS Introduction

1 INTRODUCTION
1 INTRODUCTION
When you start a program it creates a thread, as compared to the runtime system is responsible
When you start a program it creates a thread, as compared to the runtime system is responsible
for carrying out the program’s statements. You can think of a thread as a part of the program
for carrying out the program’s statements. You can think of a thread as a part of the program
code that has its own life and can be performed independent of the runtime system in
code that has its own life and can be performed independent of the runtime system in
competition with threads from other applications or a thread from the same program. In
competition with threads from other applications or a thread from the same program. In
order for a thread to run and execute anything, it must have a processor to run on, and even
order for a thread to run and execute anything, it must have a processor to run on, and even
though computers today usually have multiple processors, there will always be many more
though computers today usually have multiple processors, there will always be many more
active threads than there are processors. A thread has only a processor in a very short time,
active threads than there are processors. A thread has only a processor in a very short time,
after which it is interrupted by the system and put in a queue while another thread get the
after which it is interrupted by the system and put in a queue while another thread get the
processor. Since all threads in this way with very short time intervals will have a processor
processor. Since all threads in this way with very short time intervals will have a processor
available, it seems to us users as if all threads are running in parallel next to each other.
available, it seems to us users as if all threads are running in parallel next to each other.

When you start a program so is created, as mentioned a thread to execute the program’s
When you start a program so is created, as mentioned a thread to execute the program’s
instructions. This thread is called the primary thread. An application can, however, create
instructions. This thread is called the primary thread. An application can, however, create
multiple threads, and many programs do, and a GUI program will at least create two threads.
multiple threads, and many programs do, and a GUI program will at least create two threads.
The idea of allowing a program to create multiple threads is to achieve parallelism, so it
The idea of allowing a program to create multiple threads is to achieve parallelism, so it
for users seems as the program is doing several things simultaneously. For example a word
for users seems as the program is doing several things simultaneously. For example a word
processor can perform a spell checking while the user continues entering text. The subject
processor can perform a spell checking while the user continues entering text. The subject
of this book is to show how Java creates a thread and the challenges it leads to, but also
of this book is to show how Java creates a thread and the challenges it leads to, but also
to show what you can use threads in practice. Indeed, viewed from the programmer some
to show what you can use threads in practice. Indeed, viewed from the programmer some
challenges are attached to threads and the book contains many technical details.
challenges are attached to threads and the book contains many technical details.

1.1 CREATE A THREAD


1.1 CREATE A THREAD
I’ll start by showing how a program can create threads, and the following program creates
I’ll start by showing how a program can create threads, and the following program creates
four threads beyond the primary thread:
four threads beyond the primary thread:

package thread01;

import java.util.*;

public class Thread01


{
public static void main(String[] args)
{
(new Thread(new Worker1())).start();
new Worker2();
(new Thread(new Runnable() {
public void run() { ToDo.work(2, 5); } })).start();
(new Thread(() -> ToDo.work(2, 5))).start();

8
8
JAVA 8:MULTITHREADED PROGRAMS Introduction
JAVA 8:MULTITHREADED PROGRAMS IntroduCtIon

ToDo.work(5, 10);
}
}

class Worker1 implements Runnable


{
public void run()
{
ToDo.work(2, 5);
}
}

class Worker2 extends Thread


{
public Worker2()
{
start();
}

public void run()


{
ToDo.work(2, 5);
}
}

class ToDo
{
private static Random rand = new Random();

public static void work(int a, int b)


{
print("started");
for (int i = 0, n = rand.nextInt(b – a) + a; i < n; ++i)
{
print("working........");
work();
}
print("terminated");
}

private static void print(String text)


{
long id = Thread.currentThread().getId();
System.out.println("[" + id + "] " + text);
}

9
9
JAVA 8:MULTITHREADEDPROGRAMS
JAVA PROGRAMS Introduction
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS IntroduCtIon
IntroduCtIon

private
private static
static void
void work()
work()
{
{
double
double y;
y;
for
for (int
(int i
i== 0;
0; i
i<< 1000000L;
1000000L; ++i)
++i) y
y== Math.cos(Math.sqrt(rand.nextDouble()));
Math.cos(Math.sqrt(rand.nextDouble()));
}
}
}
}

I’ll
I’llstart
I’ll startwith
start withthe
with theclass
the classToDo,
class ToDo,which
ToDo, whichin
which ininprinciple
principledo
principle dodonot
nothave
not haveanything
have anythingwith
anything withthreads
with threadsto
threads totodo.
do.
do.
The
The class
Theclass represents
classrepresents a work
representsaawork that
workthat the
thatthe computer
thecomputer
computerhas has to perform,
hastotoperform, and
perform,and the
andthe important
theimportant thing
importantthing thing
is that
isisthat it is a work
thatititisisaawork that
workthat takes
thattakes time,
takestime, and
time,and then
andthen strains
thenstrains the
strainsthe machine’s
themachine’s processor.
machine’sprocessor. The
processor.The private
Theprivate
private
method
method work()
work() performs
performs works
works not
not used
used for
for anything
anything but
but the
the work
work
method work() performs works not used for anything but the work consists of performing consists
consists of
of performing
performing
one
onemillion
one millioncalculation
million calculationin
calculation ininwhich
whichaaacalculation
which calculationis
calculation isisto
totoperform
performaaamathematical
perform mathematicalfunction
mathematical functionwhich
function which
which
uses
uses many
usesmanymanyCPU CPU instructions.
CPUinstructions.
instructions.TheThe second
Thesecond version
secondversion of the
versionofofthe method
themethod work()
methodwork() (the
work()(the public
(thepublic version)
publicversion)
version)
has
has two
hastwo parameters,
twoparameters,
parameters,andand call
andcall the
callthe private
theprivate work()
privatework() a number
work()aanumber of times
numberofoftimes determined
timesdetermined
determinedby by
bythese
these
these
parameters.
parameters. The
The method
method first
first prints
prints a
a message
message on
on the
the screen,
screen, and
and after
after the
the
parameters. The method first prints a message on the screen, and after the work is completed, work
work is
is completed,
completed,
it
ititprints
printsanother
prints anothermessage.
another message.For
message. Forthe
For themessage
the messageyou
message youshould
you shouldnote
should notethe
note thestatement
the statement
statement

long id
long id =
= Thread.currentThread().getId();
Thread.currentThread().getId();

A
AAthread
threadis
thread isisidentified
identifiedby
identified byan
by anID,
an ID,which
ID, whichis
which isisan
aninteger
an integerand
integer andis
and isisassigned
assignedwhen
assigned whenthe
when thethread
the threadis
thread isis
created.
created. The
created.The primary
Theprimary thread
primarythread has
threadhas number
hasnumber 1, while
number1,1,while custom
whilecustom threads
customthreads are
threadsare assigned
areassigned a number
assignedaanumbernumber
from
from 10 onwards. When the method work() prints a message (the method print()),
from 10 onwards. When the method work() prints a message (the method print()), itprints
10 onwards. When the method work() prints a message (the method print()), it
it prints
prints
also
also the
alsothe current
thecurrent thread
currentthread
threadIDID (the
ID(the thread
(thethread that
threadthat performs
thatperforms the
performsthe method
themethod print()).
methodprint()).
print()).

In
InInJava
Javais
Java isisaaathread
threadis
thread isisrepresented
representedby
represented bybythetheclass
the classThread.
class Thread.The
Thread. Theclass
The classWorker2
class Worker2inherits
Worker2 inheritsthe
inherits theclass
the class
class
Thread
Thread and represents as such a thread. The class Thread has a method
Thread and represents as such a thread. The class Thread has a method called run() andit
and represents as such a thread. The class Thread has a method called
called run()
run() and
and itit
is
isisthe
themethod
the methodthat
method thatexecutes
that executeswhen
executes whenthe
when thethread
the threadis
thread isisstarted,
started,and
started, andin
and ininthis
thiscase
this caseit
case itithappens
happensin
happens ininthe
the
the
constructor
constructor of
constructorofofthe the class
theclass Worker2.
classWorker2. It is the
Worker2.ItItisisthe programmer
theprogrammer of a Thread
programmerofofaaThread class
Threadclass that
classthat must
thatmust override
mustoverride
override
the
the method
themethod
methodrun()run() and
run()and determine
anddetermine what
determinewhat
whatthethe thread
thethread
threadhashas to perform
hastotoperform
performandand the
andthe thread
thethread runs
runsuntil
threadruns until
until
the
the method run() terminates. In this case, the thread performs the
the method run() terminates. In this case, the thread performs the method work() inthe
method run() terminates. In this case, the thread performs the method
method work()
work() in
in the
the
class
class ToDo.
classToDo.
ToDo.

The
Theclass
The classThread
class Threadimplements
Thread implementsthe
implements theinterface
the interfaceRunnable,
interface Runnable,which
Runnable, whichalone
which alonedefines
alone definesthe
defines themethod
the methodrun().
method run().
run().
Another
Another way
way to
to define
define a
a thread
thread is
is to
to transfer
transfer a
a Runnable
Runnable object
object as
as a
a parameter
parameter
Another way to define a thread is to transfer a Runnable object as a parameter to the Thread to
to the
the Thread
Thread
class’s
class’sconstructor
class’s constructorand
constructor andin
and ininthis
thisway
this waytells
way tellswhat
tells whatkind
what kindof
kind ofofaaarun()
run()method
run() methodto
method totobe
beexecuted.
be executed.The
executed. The
The
class
class Worker1
classWorker1 is a simple
Worker1isisaasimple class
simpleclass that
classthat implements
thatimplements Runnable
implementsRunnable
Runnableandand thus
andthus must
thusmust implement
mustimplement
implementthethe
the
method
method run(),
methodrun(), and
run(),and the
andthe class
theclass defines
classdefines then
definesthen Runnable
thenRunnable objects.
Runnableobjects. In this
objects.InInthis case,
thiscase, the
case,the method
themethod run()
methodrun()
run()
performs
performs the
the same
same as
as in
in the
the thread
thread class
class
performs the same as in the thread class Worker2. Worker2.
Worker2.

10
10
10
JAVA 8:MULTITHREADED PROGRAMS Introduction
JAVA 8:MULTITHREADED PROGRAMS IntroduCtIon

Back’s is the main() method. The first statement creates a new Thread object and start a
Back’s is the main() method. The first statement creates a new Thread object and start a
thread. The parameter to the constructor is a Runnable object, and in this case it is an object
thread. The parameter to the constructor is a Runnable object, and in this case it is an object
of the type Worker1. The next statement starts another thread, but this time by instantiating
of the type Worker1. The next statement starts another thread, but this time by instantiating
an object of the type Worker2. Here it is the constructor of the class Worker2 that starts the
an object of the type Worker2. Here it is the constructor of the class Worker2 that starts the
thread. Then there is the third statement that does the same as the first statement and thus
thread. Then there is the third statement that does the same as the first statement and thus
starts a thread that performs the method work(), but instead to create a Runnable object of
starts a thread that performs the method work(), but instead to create a Runnable object of
the type Worker1, the statement instantiates a Runnable object using an anonymous class.
the type Worker1, the statement instantiates a Runnable object using an anonymous class.
The fourth statement does the same, but here it happens instead using a lambda expression.
The fourth statement does the same, but here it happens instead using a lambda expression.
Back there is the last statement, which simply calls the ToDo class’s work() method. That
Back there is the last statement, which simply calls the ToDo class’s work() method. That
is, it is the primary thread that performs this statement, and the meaning is that you have
is, it is the primary thread that performs this statement, and the meaning is that you have
to see that the primary thread is running in parallel with the other threads. If you executes
to see that the primary thread is running in parallel with the other threads. If you executes
the program, the result could be the following:
the program, the result could be the following:

[11] started
[10] started
[10] works........
[12] started
[11] works........
[12] works........
[1] started
[13] started
[1] works........
[13] works........
[12] works........
[13] works........
[12] works........
[12] works........
[12] terminated
[10] works........
[11] works........
[1] works........
[11] terminated
[1] works........
[10] terminated
[13] works........
[1] works........
[13] terminated
[1] works........
[1] works........
[1] works........
[1] works........
[1] terminated

11
11
JAVA 8:MULTITHREADED PROGRAMS IntroduCtIon
JAVA 8:MULTITHREADED PROGRAMS Introduction

Here you should note that the 5 threads are running on shift. When the threads are carrying
Here you should note that the 5 threads are running on shift. When the threads are carrying
out work that takes time, they are periodically interrupted, and a second pending thread is
out work that takes time, they are periodically interrupted, and a second pending thread is
running instead of. It is important to note that one can not assume anything about when a
running instead of. It is important to note that one can not assume anything about when a
thread is interrupted, and when the thread again is started. It is managed by the operating
thread is interrupted, and when the thread again is started. It is managed by the operating
system and is determined by the tasks to be performed on the machine.
system and is determined by the tasks to be performed on the machine.
1.2 THREADS PROPERTIES
1.2 THREADS PROPERTIES
I will then show an example that prints properties for a thread. The program starts two
I will then show an example that prints properties for a thread. The program starts two
threads and shows examples of information regarding the threads state. The program also
threads and shows examples of information regarding the threads state. The program also
shows how to suspend a thread, which means that the thread does not have a CPU available
shows how to suspend a thread, which means that the thread does not have a CPU available
before it is again ready.
before it is again ready.
package thread02;

public class Thread02


{
public static void main(String[] args)
{
System.out.println(
("Number of processors: " + Runtime.getRuntime().availableProcessors()));

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

12
12
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Introduction
IntroduCtIon

Thread th1 = new Thread(new InfoThread(), "Thread number one");


Thread th2 = new Thread(new InfoThread(), "Thread number two");
System.out.println(th1.getState());
// th1.setDaemon(true);
th2.setDaemon(true);
th1.start();
th2.start();
System.out.println(th1.isAlive());
}

class InfoThread implements Runnable


{
public void run()
{
Thread th = Thread.currentThread();
System.out.println("[" + th.getId() + "] " + th.getName() + " is started");
System.out.println(
"[" + th.getId() + "] " + (th.isDaemon() ? "Deamon" : "None deamon"));
System.out.println("[" + th.getId() + "] " + th.getState());
try
{
Thread.sleep(2000);
}
catch (Exception ex)
{
}
System.out.println("[" + th.getId() + "] " + th.getName() + " is terminated");
}
}

The
Thethread
threadisisdefined
definedby bythe
theclass
classInfoThread
InfoThreadthat thatimplements
implementsRunnable
Runnableand andthus
thusthe
themethod
method
run(). The method first prints the thread’s id and its name. The class Thread
run(). The method first prints the thread’s id and its name. The class Thread has a method, has a method,
sosoyou
youcancanassign
assignaathread
threadaaname,
name,but butyouyoucancanalso
alsoprovide
provideaathread
threadaanamenamewhen
whenititisis
created.
created.AAthread
threadmaymaybe beaadaemon
daemonthread
threadororaanone
nonedaemon
daemonthread
thread(also
(alsoreferred
referredtotoasasaa
worker
worker thread).
thread). AA daemon
daemon thread
thread isis intended
intended asas aa helper
helper thread
thread toto another
another thread,
thread, and
and
the difference is that a daemon thread is automatically terminated when
the difference is that a daemon thread is automatically terminated when the program’s last the program’s last
none
nonedaemon
daemonthread
threadterminates,
terminates,and andwhen
whenthe theprimary
primarythread
threadisisaanone-daemon
none-daemonthread,thread,
the
the daemon
daemon threads
threads automatically
automatically terminates
terminates when
when the the program
program terminates.
terminates. InIn contrast,
contrast,
the
theprimary
primarythread
thread(and
(andtherefore
thereforethe theprogram)
program)doesdoesnot notterminate
terminateuntil
untilall
allnone
nonedaemon
daemon
threads
threads is completed. The next print statement in the run() method prints whether the
is completed. The next print statement in the run() method prints whether the
current
currentthread
threadisisaadaemon
daemonthread.
thread.TheThethird
thirdstatement
statementprints
printsthethethread’s
thread’sstate,
state,which
whichcancanbebe

13
13
JAVA
JAVA8:MULTITHREADED
8:MULTITHREADEDPROGRAMS
PROGRAMS IntroduCtIon
Introduction

--- NEW,
NEW, aa thread
thread isis created,
created, but
but not
not yet
yet started
started
--- RUNNING,
RUNNING, the the thread
thread isis performed
performed on on aa processor
processor
--- BLOCKED,
BLOCKED, aa thread
thread isis blocked
blocked and and isis waiting
waiting onon aa lock
lock
--- WAITING,
WAITING, aa thread
thread waits
waits onon aa notification
notification from
from another
another thread
thread
--- TIMED_WAITING,
TIMED_WAITING, aa thread thread waits
waits on
on aa notification
notification because
because of
of aa timeout
timeout
--- TERMINATED,
TERMINATED, the the thread
thread isis terminated
terminated

After
After these
these three
three print
print statements
statements are are executed,
executed, thethe run()
run() method
method performs
performs aa sleep(),
sleep(), which
which
means
meansthat thatthe
thethread
threadisissuspended
suspendedfor foraacertain
certainperiod.
period.The
Thetime
timeisisspecified
specifiedin inmilliseconds,
milliseconds,
and
and inin this
this case
case the
the thread
thread isis suspended
suspended in in 22 seconds.
seconds. That
That aa thread
thread isis suspended
suspended means
means that
that
in
in the
the period
period in in question
question itit isis not
not active
active and
and does
does not
not participate
participate in
in thethe resource
resource allocation.
allocation.
Especially
Especially itit uses
uses no
no CPU
CPU time.
time. WhenWhen the the thread
thread again
again becomes
becomes active
active andand isis running,
running, itit
prints
prints another
another message
message with
with its its id
id and
and name,
name, andand then
then the
the thread
thread exits.
exits.

The
The main()
main() method
method starts
starts byby printing
printing the
the number
number of of processors
processors that that areare available
available onon the
the
current
current computer.
computer. Next,
Next, itit creates
creates two
two threads,
threads, both
both threads
threads defined
defined withwith aa Runnable
Runnable object
object
of
of type
type InfoThread
InfoThread as as parameter.
parameter. Note Note that
that the
the two
two threads
threads atat thethe same
same time
time are
are given
given aa
name.
name. Next
Next isis printed
printed thethe state
state of
of the
the first
first thread,
thread, which
which atat that
that time
time will
will bebe NEW.
NEW. ThenThen
isis defined
defined that
that the
the other
other thread
thread should
should be be aa daemon
daemon thread.
thread. Finally
Finally the the two
two threads
threads are
are
started,
started, and
and thethe main()
main() method
method prints
prints that
that the
the first
first thread
thread isis “live”.
“live”. IfIf you
you run
run the
the program,
program,
the
the result
result could
could bebe the
the following:
following:

Number of processors: 8
NEW
true
[10] Thread number one is started
[11] Thread number two is started
[10] None deamon
[10] RUNNABLE
[11] Deamon
[11] RUNNABLE
[10] Thread number one is terminated
[11] Thread number two is terminated

Here
Here you
you should
should specifically
specifically note note that
that maybe
maybe thethe last
last thread
thread notnot writes
writes that
that itit isis completed.
completed.
The
The reason
reason isis that
that itit isis aa daemon
daemon thread
thread and
and as
as soon
soon as as the
the first
first thread
thread terminates,
terminates, also also
the
the primary
primary thread
thread terminates
terminates and and thus
thus also
also the
the second
second thread.
thread. InIn the
the main()
main() methodmethod isis aa
comment
comment in in front
front ofof the
the statement
statement that
that defines
defines the
the first
first thread
thread asas aa daemon
daemon thread.
thread. IfIf you
you
remove
remove this
this comment,
comment, the the primary
primary thread
thread does
does not
not wait
wait for
for the
the two
two threads
threads and
and finish
finish with
with
the
the same
same –– and
and the
the two
two threads
threads are
are immediately
immediately terminated
terminated without
without completing
completing their their work.
work.

14
14
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Introduction
IntroduCtIon

The program
The program here
here shows
shows some
some ofof the
the properties
properties aa thread
thread can
can have
have and
and the
the services
services that
that the
the
Thread class
Thread class provides.
provides. There
There are
are other
other options
options such
such toto change
change aa thread’s
thread’s priority.
priority. You
You must,
must,
however, usually
however, usually not
not dodo that,
that, unless
unless you
you have
have aa good
good reason.
reason.

Asanother
As anotherexample
exampleof ofaaprogram
programthat
thatstarts
startsmultiple
multiplethreads,
threads,you
youcan
canconsider
considerthe
thefollowing
following
program that
program that starts
starts 100
100 threads:
threads:

package thread03;

public class Thread03


{
public static void main(String[] args)
{
for (int i = 0; i < 100; ++i) (new Thread(() -> work())).start();
}

360°
thinking .

360°
thinking . 360°
thinking .
Discover the truth at www.deloitte.ca/careers Dis

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers © Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers


15
15
JAVA 8:MULTITHREADED PROGRAMS Introduction
JAVA 8:MULTITHREADED PROGRAMS IntroduCtIon

private static void work()


{
print("Startet");
double y = 0;
for (int i = 0; i < 10000000L; ++i) y = Math.cos(Math.sqrt(2));
print(String.format("%1.4f", y));
}

private static void print(String text)


{
System.out.println("[" + Thread.currentThread().getId() + "] " + text);
}
}

Compared to the two first examples there are nothing new, but the program should show
Compared to the two first examples there are nothing new, but the program should show
what happens if you start many threads, all of which are CPU intensive. There are started
what happens if you start many threads, all of which are CPU intensive. There are started
100 threads, but what matters is that there are started many more threads than there are
100 threads, but what matters is that there are started many more threads than there are
CPUs. If the program is performed, you must observe that all threads are started but prints
CPUs. If the program is performed, you must observe that all threads are started but prints
the start message in unpredictable order. In turn, the threads performs their work until
the start message in unpredictable order. In turn, the threads performs their work until
they quit, and again the order is unpredictable. It depends on when the operating system
they quit, and again the order is unpredictable. It depends on when the operating system
interrupts the threads and decides which threads should be started again.
interrupts the threads and decides which threads should be started again.

EXERCISE 1
EXERCISE 1
Write a program that creates and starts two threads. The one thread must perform a loop
Write a program that creates and starts two threads. The one thread must perform a loop
that iterates 10 times. For each iteration, the thread should print an integer between 0
that iterates 10 times. For each iteration, the thread should print an integer between 0
and 99, after which it must be suspended for a random period less than one second. The
and 99, after which it must be suspended for a random period less than one second. The
second thread should act in the same way, but instead print a random decimal number.
second thread should act in the same way, but instead print a random decimal number.
My solution is called StartThreads.
My solution is called StartThreads.

16
16
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS joIn
join

2 JOIN
2 JOIN
Consider
Consider the
the following
following program:
program:

package thread04;

public class Thread04


{
private static long prime;

public static void main(String[] args)


{
Thread th;
(th = new Thread(() -> nextPrime(10000000))).start();
System.out.println(prime);
}

private static void nextPrime(long t)


{
if (t < 2) prime = 2;
else for (prime = t % 2 == 0 ? t + 1 : t; !isPrime(prime); prime += 2);
}

private static boolean isPrime(long t)


{
if (t == 2 || t == 3 || t == 5 || t == 7) return true;
if (t < 11 || t % 2 == 0) return false;
for (long k = 3, m = (long)Math.sqrt(t) + 1; k <= m; k += 2)
if (t % k == 0) return false;
return true;
}
}

The method nextPrime() determines the first prime number that is greater than or equal to
The method nextPrime() determines the first prime number that is greater than or equal to
the parameter t. It is a method that I have shown before, and here it is interesting that if
the parameter t. It is a method that I have shown before, and here it is interesting that if
the parameter t is large, it may take a long time to perform the method. In main() is created
the parameter t is large, it may take a long time to perform the method. In main() is created
a thread that performs the method, and then print the result as the value of the variable
a thread that performs the method, and then print the result as the value of the variable
prime. The program will print 0, which of course is wrong. The reason is that the primary
prime. The program will print 0, which of course is wrong. The reason is that the primary
thread continues after the thread th is started and print the value of prime within the thread
thread continues after the thread th is started and print the value of prime within the thread
has updated the variable. The primary thread does not wait for the thread th to terminate.
has updated the variable. The primary thread does not wait for the thread th to terminate.

17
17
JAVA 8:MULTITHREADED PROGRAMS join
JAVA 8:MULTITHREADED PROGRAMS joIn

The problem can be solved by changing the main() method to the following:
The problem can be solved by changing the main() method to the following:

public static void main(String[] args)


{
Thread th;
(th = new Thread(() -> nextPrime(10000000))).start();
try
{
th.join();
}
catch (Exception ex)
{
}
System.out.println(prime);
}

A thread has a method called join(). If another thread – and here is the primary thread –
A thread has a method called join(). If another thread – and here is the primary thread –
is performing the method join() on a Thread object, it means that the second thread must
is performing the method join() on a Thread object, it means that the second thread must
wait until the first thread terminates. In this case, this means that the last print statement
wait until the first thread terminates. In this case, this means that the last print statement
is not performed before the thread th has calculated the result and terminates.
is not performed before the thread th has calculated the result and terminates.

We will turn your CV into


an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

18

18
JAVA 8:MULTITHREADED PROGRAMS joIn

JAVA 8:MULTITHREADED PROGRAMS joIn


JAVA 8:MULTITHREADED PROGRAMS join
EXERCISE 2
EXERCISE
In 22 you should use the methods nextPrime() and isPrime() from the above
this exercise,
EXERCISE
example,
In this the first to
this exercise,
exercise, youbeshould
modified
should useslightly.
the methods
methods nextPrime()
nextPrime() and
and isPrime()
isPrime() from
from the
the above
above
In you use the
example, the
example, the first
first to
to be
be modified
modified slightly.
slightly.
Create a new project, you can call JoinThreads. Start by adding the following class, which
are nothing
Create more than you
a simple encapsulation
JoinThreads.ofStart
a longby: adding the following class, which
Create aa new
new project,
project, can call
you can call JoinThreads. Start by adding the following class, which
are nothing
are nothing more
more thanthan aa simple
simple encapsulation
encapsulation ofof aa long :
long :
class Prime
{
class Prime
private long value;
{
private long value;
public long getValue()
{
public long getValue()
return value;
{
}
return value;
}
public void setValue(long value)
{
public void setValue(long value)
this.value = value;
{
}
this.value = value;
}
}
}
You must then add the following class, which defines a Runnable object:
You must then add the following class, which defines a Runnable object:
You must then add the following class, which defines a Runnable object:
class Creator implements Runnable
{
class Creator implements Runnable
private long value;
{
private Prime prime;
private long value;
private Prime prime;
public Creator(long value, Prime prime)
{
public Creator(long value, Prime prime)
this.value = value;
{
this.prime = prime;
this.value = value;
}
this.prime = prime;
}
public void run()
{
public void run()
nextPrime(value, prime);
{
}
nextPrime(value, prime);
}
public static void nextPrime(long t, Prime prime)
{
public static void nextPrime(long t, Prime prime)
}
{
}
}
}

19

19
19
JAVA 8:MULTITHREADED
JAVA 8:MULTITHREADED PROGRAMS
PROGRAMS joIn
join

The method
The method nextPrime()
nextPrime() is,is, in
in principle,
principle, the
the same
same method
method as as the
the method
method in in the
the above
above
example, but
example, but itit now
now has
has an
an additional
additional parameter.
parameter. The
The method
method must
must set
set the
the value
value of of the
the
object to
object to the
the first
first prime
prime number
number that
that is
is greater
greater than
than or
or equal
equal to
to t.
t. Note
Note that
that it
it is
is still
still aa static
static
method and
method and it
it is
is placed
placed in
in this
this class
class because
because of
of the
the method
method run()
run() that
that refer
refer to
to nextPrime().
nextPrime().

Then
Then write the
write the following
following main()
main() method,
method, which
which determines
determines 13
13 “large”
“large” primes
primes and
and print
print
them
them on the
on the screen:
screen:

public static void main(String[] args)


{
long[] values =
{ 1000000, 10000000, 100000000, 1000000000, 10000000000L, 100000000000L,
1000000000000L, 10000000000000L, 100000000000000L, 1000000000000000L,
10000000000000000L, 100000000000000000L, 1000000000000000000L };
Prime[] primes = new Prime[values.length];
for (int i = 0; i < primes.length; ++i) primes[i] = new Prime();
for (int i = 0; i < values.length; ++i) Creator.nextPrime(values[i], primes[i]);
for (int i = 0; i < primes.length; ++i) System.out.println(primes[i].getValue());
}

The most
The most important
important isis the
the statement,
statement, which
which calls
calls the
the method
method nextPrime()
nextPrime() 13
13 times.
times. You
You
must now
must now change
change the
the main()
main() method,
method, so
so each
each call
call of
of the
the method
method nextPrime()
nextPrime() is
is performed
performed
in its
in its own
own thread.
thread. You
You can
can of
of course
course use
use the
the class
class Creator
Creator to
to create
create Runnable
Runnable objects.
objects.

After making
After making this
this changes,
changes, try
try if
if you
you can
can observe
observe aa time
time differences
differences in
in terms
terms where
where the
the
prime numbers
prime numbers are
are generated
generated sequentially
sequentially or
or in
in separate
separate threads.
threads.

20
20
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS synChronIzatIon oF threads
Synchronization of threads

3
3 SYNCHRONIZATION OF THREADS
As
As shown
shown in in the
the initial
initial examples
examples it it is
is easy
easy to
to create
create and
and use
use threads
threads inin aa program,
program, and
and so
so
long
long that
that the
the individual
individual threads
threads dodo not
not share
share resources, the use
resources, the use of
of threads
threads are
are also
also without
without
major
major problems,
problems, but but if
if threads
threads share
share common
common resources,
resources, they
they can
can cause
cause concurrency
concurrency problems
problems
that
that must be solved by the programmer, and it does absolutely not to be simple. The typical
must be solved by the programmer, and it does absolutely not to be simple. The typical
problem is
problem is the
the so-called
so-called race
race conditions,
conditions, where
where thethe result
result ofof aa calculation
calculation depends
depends onon the
the
timing
timing of
of the
the threads
threads access
access to
to aa shared
shared resource,
resource, andand the
the classic
classic example
example is is that
that two
two or
or more
more
threads
threads use a common data element (a variable), and at least one of the threads change the
use a common data element (a variable), and at least one of the threads change the
value
value of the variable, but without the threads coordinates their use of the data item. As an
of the variable, but without the threads coordinates their use of the data item. As an
example, consider
example, consider the
the following
following method:
method:

public int getId()


{
return counter++;
}

21
21
JAVA 8:MULTITHREADED PROGRAMS Synchronization of threads

where counter is an instance variable, and such a method is not thread safe. Apparently, the
method performs only one operation, but there are several

1. save a copy of the variable counter


2. add 1 to the value og the variable
3. save the result in counter
4. returns the value, that has been saved

If, you for example imagine that two threads that calls this method, and counter has the value
10, the following can happen: The first thread performs the first of the above instructions,
after which it is interrupted. Next comes the second thread and performs the first three
operations. Then, the counter has the value 11. If the second thread now is interrupted,
and the first thread comes back and finished its work, it will update counter so that it has
the value 11 (and thus overwrite the changes that the other thread has done). The result
is that both threads will return 11, which is an incorrect result, and the value of counter
is incorrect. The conclusion is the need for a mechanism that can control that the threads
are finished their work, or at least that another thread may not use the method before the
first is completed.

To increase performance using both the Java virtual machine (JVM) and the operating
system cache memories, where they keep copies of variables. This can also cause problems,
since each thread possible has their own copy of a variable. If a thread modifies a variable,
there is a risk that it is merely the copy that is updated, and without the other threads
being aware of it, and they updates their own copies. It is also an issue that multithreaded
applications must relate to.

The solution to these challenges is synchronization and locks, which ensures that the two
or more threads can not simultaneously execute a critical region, which is a number of
operations to be performed serially. Sometimes people talk about mutual exclusion as a
thread is prevented to perform a critical region, as another thread is performing. A critical
region is defined by the word synchronized, and in addition to ensure that other threads
can not access the critical region it also ensures that variables values are synchronized with
memory, when the region ends. Each Java object is associated with a so-called monitor,
which has a lock which only one thread may have, and if a thread has a lock, other threads
can not apply the critical region before the thread that has the lock is releasing it. There
is only one thread which can have the lock, and if a different thread attempts to get the
lock, it will be blocked until the first release the lock.

22
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS synChronIzatIon
Synchronization oF
of threads
threads

Consider
Consider the
the following
following program:
program:

package thread05;
public class Thread05
{
private static ID id = new ID();

public static void main(String[] args)


{
for (int i = 0; i < 2; ++i)
(new Thread(() ->
{ while (id.getValue() < 10)
System.out.println(String.format(
"[%d] %d", Thread.currentThread().getId(), id.getId()));
}
)).start();
}
}

class ID
{
private int id = 1;

public int getValue()


{
return id;
}

public int getId()


{
int t = id;
for (int i = 0; i < 1000000L; ++i) Math.cos(Math.sqrt(2));
++id;
return t;
}
}

23
23
JAVA 8:MULTITHREADED PROGRAMS synChronIzatIon oF threads
JAVA 8:MULTITHREADED PROGRAMS Synchronization of threads

The program illustrates some of the problems that can occur when multiple threads are using
The program illustrates some of the problems that can occur when multiple threads are using
a shared resource, that here is an ID object. The problem is that the same ID is printed
a shared resource, that here is an ID object. The problem is that the same ID is printed
several times and that some values are lost. The reason is that the operation getId() in the
several times and that some values are lost. The reason is that the operation getId() in the
class ID takes a long time, and thus is interrupted, so another thread can take over. The
class ID takes a long time, and thus is interrupted, so another thread can take over. The
method which returns the value of variable id, but also counted the variable up by 1. The
method which returns the value of variable id, but also counted the variable up by 1. The
method also carries out a number of operations that takes time. It should illustrate that
method also carries out a number of operations that takes time. It should illustrate that
the method performs work between the variable is read and counted, and thus the method
the method performs work between the variable is read and counted, and thus the method
can be interrupted during that period. The main() method starts two threads, where each
can be interrupted during that period. The main() method starts two threads, where each
thread iterates so long that the value of the object id is less than 10. Each iteration reads
thread iterates so long that the value of the object id is less than 10. Each iteration reads
the ID object (and hence counts the value of the variable up by 1) and also at the same
the ID object (and hence counts the value of the variable up by 1) and also at the same
time prints the thread’s ID and the value of the object ID. If you executes the program,
time prints the thread’s ID and the value of the object ID. If you executes the program,
the result could be the following:
the result could be the following:
[10] 1
[11] 1
[10] 3
[11] 3
[11] 5
[10] 5
[11] 6
[10] 6

AXA Global
Graduate Program
Find out more and apply

24
24
JAVA 8:MULTITHREADED PROGRAMS synChronIzatIon oF threads
JAVA 8:MULTITHREADED
JAVA 8:MULTITHREADED PROGRAMS
PROGRAMS Synchronization oF
synChronIzatIon of threads
threads

[11] 7
[11]
[10] 7
7
[10]
[11] 7
8
[11]
[10] 8
8
[10]
[11] 8
9
[11]
[10] 9
9
[10] 9

where
where you
you can
can see
see that
that both
both threads
threads prints
prints the
the same
same value,
value, while
while other
other values
values are
are ignored.
ignored.
where you can see that both threads prints the same value, while other values are ignored.
The reason
The reason is
reason is that
is that the
that the two
the two threads
two threads are
threads are updating
are updating a shared
updating aa shared resource
shared resource id,
resource id, but
id, but change
but change
change itit
it without
without
The without
being synchronized.
being synchronized.
synchronized. The The problem
The problem can
problem can be
can be solved
be solved
solved byby modify
by modify the
modify the class
the class ID
class ID as
ID as follows,
follows, where
as follows, where
being where
the method
the method getId()
method getId()
getId() isis now
is now defined
now defined synchronized:
defined synchronized:
synchronized:
the
class ID
class
{ ID
{private int id = 1;
private int id = 1;

public int value()


public
{ int value()
{ return id;
} return id;
}

public synchronized int getId()


public
{ synchronized int getId()
{ int t = id;
int
for t = id;
(int i = 0; i < 1000000L; ++i) Math.cos(Math.sqrt(2));
for (int
++id; i = 0; i < 1000000L; ++i) Math.cos(Math.sqrt(2));
++id;
return t;
} return t;
}}
}

When a method is synchronized, it means that the whole operation is indivisible and is
When
When aaasmethod
method is
is synchronized,
synchronized, it
it means
means that the whole operation is
is indivisible and is
viewed a critical region. If a thread calls that
the the wholeand
method operation
the method indivisible
is not used andbyis
viewed
viewed asas a critical
a critical region.
region.may If a thread
If agetthread calls the
callsand method
theifmethod and the method is not used by
another thread, the thread the lock, another and
threadthethen
method is not
attempts used by
to perform
another
another thread,
thread, the thread may get the lock, and if another thread then attempts to perform
the method, it isthe
putthread may get
in a queue and themust
lock,waitanduntil
if another thread
the first threadthen
to attempts
completestotheperform
work
the method,
the method, it is put
it islock.
put inin a queue
a queue and
and thatmust wait
mustiswait until the
until the isfirst
first thread to completes the work
and releases the If the method synchronized, anthread to method,
instance completesthe thelock
workis
and releases
and releases the
thethe lock.
lock. If the method
If theonmethod that is
thatmethodsynchronized,
is synchronized, is an instance method, the lock is
associated with object which the is called.isIfan
theinstance
methodmethod, the lock
on the other handis
associated
associated with the
with thethe object
object on which the method is called. If the method on the other hand
is a static method lockon which the to
is associated method is called. If the
the java.lang.Class method
object on class
for the the other
wherehand
the
is
is a
a static
static method
method the
the lock
lock is
is associated
associated to
to the
the java.lang.Class
java.lang.Class object
object for
for the
the class
class where
where the
the
method belongs.
method belongs.
method belongs.

25
25
25
JAVA 8:MULTITHREADED PROGRAMS synChronIzatIon oF threads
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS synChronIzatIon
Synchronization oF
of threads
threads

Consider the following program which initializes a variable to the square root of 2, and
Consider
Consider the
the following
following program
program which
which initializes
initializes aa variable
variable to
to the
the square
square root
root of
of 2,
2, and
and
the print result:
the
the print
print result:
result:
package thread07;
package thread07;

public class Thread07


public class Thread07
{
{
private static double root = 0;
private static double root = 0;

public static void main(String[] args)


public static void main(String[] args)
{
{
(new Thread(() -> { root = sqrt2(); })).start();
(new Thread(() -> { root = sqrt2(); })).start();
System.out.println(root);
System.out.println(root);
}
}

private static double sqrt2()


private static double sqrt2()
{
{
double y = 0;
double y = 0;
for (int i = 0; i < 1000000000L; ++i) y = Math.sqrt(2);
for (int i = 0; i < 1000000000L; ++i) y = Math.sqrt(2);
return y;
return y;
}
}
}
}

The method, which determines the square root of 2 is once again a loop whose sole purpose
The method, which determines the square root of 2 is once again a loop whose sole purpose
is that the calculation must take time. The calculation is performed in its own thread, and
is that the calculation must take time. The calculation is performed in its own thread, and
when the primary thread prints the result, the result will be 0, which of course is wrong. The
when the primary thread prints the result, the result will be 0, which of course is wrong. The
reason is that the primary thread does not wait for the thread that performs the calculation,
reason is that the primary thread does not wait for the thread that performs the calculation,
and the problem could of course be solved by a join(). However, you can also solve the
and the problem could of course be solved by a join(). However, you can also solve the
problem by synchronized and thus with a lock:
problem by synchronized and thus with a lock:

package thread08;
package thread08;
public class Thread08
public class Thread08
{
{
private static double root = 0;
private static double root = 0;
private static final Object lock = new Object();
private static final Object lock = new Object();

public static void main(String[] args)


public static void main(String[] args)
{
{
(new Thread(() -> { synchronized(lock) { root = sqrt2(); }})).start();
(new Thread(() -> { synchronized(lock) { root = sqrt2(); }})).start();
try { Thread.sleep(10); } catch (Exception ex) {}
try { Thread.sleep(10); } catch (Exception ex) {}
synchronized(lock) { System.out.println(root); };
synchronized(lock) { System.out.println(root); };
}
}

26
26
26
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS SynchronizationoF
synChronIzatIon ofthreads
threads
JAVA 8:MULTITHREADED PROGRAMS synChronIzatIon oF threads

private static double sqrt2()


private static double sqrt2()
{
{
double y = 0;
double y = 0;
for (int i = 0; i < 1000000000L; ++i) y = Math.sqrt(2);
for (int i = 0; i < 1000000000L; ++i) y = Math.sqrt(2);
return y;
return y;
}
}
}
}

The
Thevariable
variablelock
lockis used
usedfor
foraaalock,
lock,and
andas mentioned,
mentioned,there
thereis attached
attachedaaalock
lockto any
anyobject.
The variable lock isisused for lock, and asasmentioned, there isisattached lock totoany object.
object.
The first
Thefirst statement
firststatement in main()
statementininmain() creates
main()creates a thread,
createsaathread, and
thread,and here
andhere is the
hereisisthe block
theblock
block
The
{ root = sqrt2(); }
{ root = sqrt2(); }

synchronized.
synchronized.TheThesame
sameapplies
appliesto the
theblock
blockwithwiththe
thelast
lastprint
printstatement.
statement.When
Whenthe thethread
synchronized. The same applies totothe block with the last print statement. When the thread
thread
starts, the
starts,the block
theblock of code
blockofofcode that
codethat call
thatcall sqrt2()
callsqrt2() is synchronized.
sqrt2()isissynchronized.
synchronized.When When
Whenthe the primary
theprimary thread
threadthen
primarythread then
starts, then
attempts to perform
attemptstotoperform
performthethe block
theblock with
blockwith the
withthe print
theprint statement
printstatement it will
statementititwill be
willbe blocked
beblocked because
blockedbecause
becausethethe lock
thelock
lock
attempts
associated with
associatedwith the
withthe object
theobject lock
objectlock is taken
lockisistaken and
takenand the
andthe primary
theprimary threads
primarythreads must
threadsmust wait
mustwait until
waituntil the
untilthe method,
themethod,
method,
associated
which performs
whichperforms the
performsthe calculation
thecalculation is complete
calculationisiscomplete
completeand and releases
andreleases the
releasesthe lock.
thelock.
lock.
which

I joined MITAS because �e Graduate Programme


for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work helping foremen advis
he
International
al opportunities
Internationa
work
�ree woor placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
work
�ree wo or placements ssolve pr

27
27
27
JAVA 8:MULTITHREADED PROGRAMS synChronIzatIon oF threads
JAVA 8:MULTITHREADED PROGRAMS Synchronization of threads

You should note that the object lock is defined final. This ensures that the object is not
You should note that the object lock is defined final. This ensures that the object is not
cached and the threads thus always refers to the memory version. You should also note that
cached and the threads thus always refers to the memory version. You should also note that
the main() method performs a sleep(). It should not be there, but is necessary, else you can
the main() method performs a sleep(). It should not be there, but is necessary, else you can
risks that the primary thread takes the lock before the calculating thread takes it.
risks that the primary thread takes the lock before the calculating thread takes it.

EXERCISE 3
EXERCISE 3
Create a project that you can call BufferProgram. In the book Java 4 there is a project called
Create a project that you can call BufferProgram. In the book Java 4 there is a project called
Generic. The project has a class called Buffer. The class represents a generic circular buffer.
Generic. The project has a class called Buffer. The class represents a generic circular buffer.
Copy this class to the current project. It is necessary with a few changes:
Copy this class to the current project. It is necessary with a few changes:

1. The class implements an interface. Remove the implements part, such the class
1. The class implements an interface. Remove the implements part, such the class
does not implement any interface.
does not implement any interface.
2. The constructor calls a method createArray(). This method is not part of the class
2. The constructor calls a method createArray(). This method is not part of the class
buffer. Extend the class Buffer with a corresponding method.
buffer. Extend the class Buffer with a corresponding method.

Write the following main() program:


Write the following main() program:
package bufferprogram;

public class BufferProgram


{
private static Buffer<Integer> buffer = new Buffer(10);

public static void main(String[] args)


{
(new Thread(new Runnable()
{
public void run()
{
for (int n = 1; ;)
if (!buffer.full()) try { buffer.insert(n++); } catch (Exception ex) {}
}
})).start();
(new Thread(new Runnable()
{
public void run()
{
while (true)
if (!buffer.empty())
try { System.out.println(buffer.remove()); } catch (Exception ex) {}
}
})).start();
}
}

28
28
JAVA 8:MULTITHREADED PROGRAMS Synchronization of threads

That is, a program that starts two threads, where the one fills numbers in a buffer, while
the other removes the numbers from the buffer. Both threads will run indefinitely. Test the
program. You will find that the program starts fine, but after a short time it goes to a halt.
The reason is that the class buffer is not thread safe.

You now need to modify the class Buffer, so it is thread safe. You can do this by defining
all the public methods synchronized. Check if the problem persists.

93%
OF MIM STUDENTS ARE
WORKING IN THEIR SECTOR 3 MONTHS
FOLLOWING GRADUATION

MASTER IN MANAGEMENT
• STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES
Length: 1O MONTHS
THAT THE CAPITAL OF SPAIN OFFERS
Av. Experience: 1 YEAR
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
Language: ENGLISH / SPANISH
PROFESSIONAL GOALS
Format: FULL-TIME
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
Intakes: SEPT / FEB
EXPERIENCE

5 Specializations #10 WORLDWIDE 55 Nationalities


MASTER IN MANAGEMENT
Personalize your program FINANCIAL TIMES
in class

www.ie.edu/master-management mim.admissions@ie.edu Follow us on IE MIM Experience

29
JAVA
JAVA8:MULTITHREADED
8:MULTITHREADEDPROGRAMS
PROGRAMS deadloCk
Deadlock

44 DEADLOCK
DEADLOCK
Synchronization
Synchronization and and locks
locks means
means thatthat threads
threads are
are blocked
blocked and and put
put inin aa waiting
waiting position,
position,
and
and itit may
may lead lead to
to deadlock.
deadlock. ItIt cancan happen
happen ifif two
two threads
threads must
must use
use two
two shared
shared resources
resources
AA and
and B. B. IfIf one
one thread
thread puts
puts aa lock
lock onon A,
A, while
while the
the other
other thread
thread puts
puts aa lock
lock on
on B,
B, and
and ifif
the
the first
first thread
thread then
then tries
tries to
to get
get the
the lock
lock on
on the
the BB (what
(what itit can
can not),
not), and
and the
the second
second thread
thread
attempts
attemptsto togetgetthe
thelock
lockononAA(what
(whatititcancannot),
not),there
thereisisaadeadlock.
deadlock.As Asananexample
exampleisisbelow
below
shown
shown aa program
program whichwhich provoke
provoke deadlock
deadlock andand the
the program
program “hangs”:
“hangs”:

package thread09;

public class Thread09


{
private final Object lock1 = new Object();
private final Object lock2 = new Object();

private static int count = 0;

public static void main(String[] args)


{
final Thread09 instance = new Thread09();
(new Thread(() -> {
while(true) { instance.work1(); instance.delay();} })).start();
(new Thread(() -> {
while(true) { instance.work2(); instance.delay();} })).start();
}

public void work1()


{
synchronized(lock1)
{
synchronized(lock2)
{
System.out.println(
"[" + Thread.currentThread().getId() + "] " + (++count));
}
}
}

30
30
JAVA 8:MULTITHREADED PROGRAMS Deadlock
JAVA 8:MULTITHREADED PROGRAMS deadloCk

public void work2()


{
synchronized(lock2)
{
synchronized(lock1)
{
System.out.println(
"[" + Thread.currentThread().getId() + "] " + (++count));
}
}
}

private void delay()


{
try
{
Thread.sleep(50);
}
catch (Exception ex)
{
}
}
}

That
Thatthreads
threadscan
canlead
leadtotodeadlock
deadlockdoes
doesnot
notmean
meanthat
thatone
oneshould
shouldavoid
avoidtotosynchronize
synchronize
threads
threads (above is a direct provocation), but it means that you have to be awareififaathread
(above is a direct provocation), but it means that you have to be aware thread
with
withaalock
lockcalls
callsaamethod
methodthatthatindirectly
indirectlyalso
alsoputs
putsaalock.
lock.

31
31
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS stop
Stop a
a thread
thread

5
5 STOP A THREAD
The
The Thread
Thread class
class has
has aa method
method stop(),
stop(), which
which isis used
used to
to stop
stop aa running
running thread.
thread. This
This method
method
isis not
not secure
secure and
and isis defined
defined deprecated,
deprecated, and
and youyou should
should avoid
avoid using
using the
the method.
method. Instead
Instead
you
you must
must yourself
yourself implement
implement the
the necessary
necessary logic
logic to
to stop
stop the
the thread.
thread. There
There can
can be
be many
many
solutions,
solutions, but
but the
the following
following program
program shows
shows an
an option:
option:

package thread10;

import java.util.*;

public class Thread10


{
public static void main(String[] args)
{
ArrayList<AThread> threads = new ArrayList();
for (int i = 0; i < 5; ++i) threads.add(new AThread());
for (AThread th : threads) th.start();
try
{
Thread.sleep(1000);
}
catch (InterruptedException ie)
{
}
for (AThread th : threads) th.stopThread();
}
}

class AThread extends Thread


{
private volatile boolean stopped = false;

public void run()


{
while(!stopped)
System.out.println(Thread.currentThread().getId() + " is running");
}

public void stopThread()


{
stopped = true;
}
}

32
32
JAVA 8:MULTITHREADED PROGRAMS Stop a thread

The principle is very simple, as the Thread class has a variable stopped and the thread is
running as long as this variable is false. The class also has a method stopThread(), which
makes the variable true and thus stops the thread. You should note that the variable stopped is
defined volatile, which means that there is no reference to a copy of the variable in a cache.

33
JAVA
JAVA8:MULTITHREADED
8:MULTITHREADEDPROGRAMS
PROGRAMS waIt()
wait()and
andnotIFy()
notify()

66 WAIT()
WAIT() AND
AND NOTIFY()
NOTIFY()
When
Whenaathread
threadofofoneonereason
reasonororanother
anotherisisblocked,
blocked,ititwill
willlost
lostthe
theprocessor
processorandandisisplaced
placedinin
aa queue
queue of
of waiting
waiting threads.
threads. AA thread
thread isis blocked
blocked because
because oneone oror other
other condition
condition occurs
occurs (for
(for
example because it can not get a lock) and must then be notified again
example because it can not get a lock) and must then be notified again when the blocking when the blocking
condition
conditionisisnonolonger
longerthere
there(for
(forexample
exampleanother
anotherthread
threadreleases
releasesaalock).
lock).AnAnobject
objecthashastwo
two
methods,
methods, so so the
the thread
thread that
that uses
uses the
the object,
object, can
can block
block itself,
itself, and
and so
so the
the thread
thread can
can give
give
waiting
waitingthreads
threadsaamessage
messagethatthatthey
theymust
mustcontinue.
continue.The
Themethods
methodsare arecalled
calledwait()
wait()and
andnotify().
notify().

AA wait()
wait() means
means that
that the
the current
current thread
thread isis blocked
blocked until
until another
another thread
thread performs
performs notify()
notify() or
or
notifyAll().
notifyAll(). There
There are
are also
also versions
versions of
of wait(),
wait(), where
where you
you enter
enter aa time,
time, telling
telling how how long
long the
the
thread
thread maximum
maximum should
should waits
waits and
and isis thus
thus aa timeout.
timeout. notify()
notify() reactivates
reactivates (wakes)
(wakes) aa waiting
waiting
thread
thread (a thread waiting on that object’s lock). If there are multiple threads waiting onthat
(a thread waiting on that object’s lock). If there are multiple threads waiting on that
object,
object, you
you can
can not
not assume
assume anything
anything about
about the
the thread
thread that
that comes
comes to to life.
life. ItIt isis determined
determined
by
by the
the system.
system. The
The method
method notifyAll()
notifyAll() will
will in
in contrast
contrast awaken
awaken all all threads
threads waiting
waiting for for the
the
current
current object.
object.

As
As aa classic
classic example
example ofof the
the use
use of of these
these methods
methods II will
will look
look atat the
the so-called
so-called producer-
producer-
consumer
consumer problem.
problem. The
The idea
idea isis that
that aa thread
thread (producer)
(producer) update
update aa resource
resource while
while another
another
thread
thread (consumer)
(consumer) reads
reads the
the resource’s
resource’s value.
value. ItIt must
must be
be such
such that
that the
the consumer
consumer reads
reads all
all
values, but only read them once. This requires that the two threads
values, but only read them once. This requires that the two threads are synchronized.are synchronized.

package thread11;

public class Thread11


{
public static void main(String[] args)
{
Shared shared = new Shared(); // the shared resource
new Producer(shared).start();
new Consumer(shared).start();
}
}

// Represents a shared resource, as an encapsulation of a char.


class Shared
{
private char value; // the resource
// indicates where the resourcen must be updated
private volatile boolean writeable = true;

34
34
JAVA 8:MULTITHREADED PROGRAMS wait() and notify()
JAVA 8:MULTITHREADED PROGRAMS waIt() and notIFy()

// Updates the resource


public synchronized void setValue(char value)
{
// if the resource can not be updated the thread performs a wait()
// on the current object, which means that the thread is suspended
// and release the lock, such that other threads can use the object
while (!writeable)
try
{
wait();
}
catch (InterruptedException ex)
{
}

// updates the resource and change status on writeable


// remark that if a thread reach the next statement it has the lock
// and other threads can not perform setValue() or getValue()
// before this thread terminates
this.value = value;
writeable = false;

// performs a notify() on the current object


// this means, that if other threads are waiting on the lock
// one of them come to life
notify();
}

// Read the shared resource.


synchronized char getValue()
{
// if the resource is writeable and it has to be updated the current
// thread performs a wait()
while (writeable)
try
{
wait();
}
catch (InterruptedException ex)
{
}

35
35
JAVA 8:MULTITHREADED PROGRAMS wait() and notify()
JAVA 8:MULTITHREADED PROGRAMS waIt() and notIFy()

// changes status on writeable and send a notifikation to other threads


// that are waiting on this object, and one of them come to life
writeable = true;
notify();
return value;
}
}

// Represents the producer


class Producer extends Thread
{
private final Shared shared; // reference to the shared resourc

public Producer(Shared shared)


{
this.shared = shared;
}

public void run()


{
for (char ch = 'A'; ch <= 'Z'; ++ch) shared.setValue(ch);
}
}

Excellent Economics and Business programmes at:

“The perfect start


of a successful,
international career.”

CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www.rug.nl/feb/education

36
36
JAVA 8:MULTITHREADED
JAVA 8:MULTITHREADED PROGRAMS
PROGRAMS wait() and
waIt() and notIFy()
notify()
JAVA 8:MULTITHREADED PROGRAMS waIt() and notIFy()

// Represents the consumer


// Represents
class Consumer the consumer
extends Thread
class
{ Consumer extends Thread
{private final Shared shared; // reference to the shared resourc
private final Shared shared; // reference to the shared resourc

public Consumer(Shared shared)


public
{ Consumer(Shared shared)
{ this.shared = shared;
} this.shared = shared;
}

public void run()


public
{ void run()
{char ch;
char
do ch;
do
{
{ System.out.print(ch = shared.getValue());
} System.out.print(ch = shared.getValue());
}
while (ch != 'Z');
while (ch != 'Z');
System.out.println();
} System.out.println();
}}
}

The program
The program prints
prints aa line
line consisting
consisting of of the
the letters
letters from
from AA to to ZZ –– in
in the
the right
right order!
order! The
The
The program
comments printsexplain
should a line consisting
how the of the letters
the program
program works,from A
but you
youto should
Z – in notice
the right order!thing.
The
comments should explain how works, but should notice aa single
single thing.
comments
The methods
methods should explainand
getValue() how the program
setValue() theworks,
in the but you
class Shared
Shared should anotice
performs a single
wait(). thing.
This method
method
The getValue() and setValue() in class performs a wait(). This
The methods getValue() and setValue() in the class andShared performs a wait(). This method
isis always
always performed
performed depending
depending on aa condition
on condition and aa call
call of
of the
the method
method must
must be done
be done in in
isa always performed
loop, such
such the depending
the condition on
condition isis tested a condition
tested before
before and and
and after a call
after the of
the wait()the method
wait() method. must
method. Otherwise be done
Otherwise there in
there isis
a loop,
aa loop, suchthe
risk that
that thewait()
condition
blocksis tested before anditafter thecomes
wait()tomethod. Otherwise therealso
is
a risk the wait() blocks aa thread
thread so that
so that never
it never comes to life again.
life again. You should
You should also
anote
risk that
that the
the wait()
wait() and
blocks a thread
notify() so thatused
are always
always it never comes to life again. You should also
in pairs.
pairs.
note that the wait() and notify() are used in
note that the wait() and notify() are always used in pairs.
EXERCISE 44
EXERCISE
EXERCISE 4
Youmust
You mustwrite
writeaaprogram
programthat
thatyou
youcan
cancall
callProducerConsumer1.
ProducerConsumer1.The Theprogram
programhas
hastotoillustrate
illustrate
You must
the same write a
same problem program
problem as that
as above, you
above, but can
but there call
there mustProducerConsumer1.
must be
be two The
two differences:
differences: program has to illustrate
the
the same problem as above, but there must be two differences:
1. the
1. the producer
producer must
must “produce”
“produce” all
all characters
characters with
with code
code from
from 33–127
33–127 (and(and not
not just
just
1. the producer
the characters must
characters from “produce”
from AA to to Z)
Z) all characters with code from 33–127 (and not just
the
the
2. Therecharacters
There must
must be from
be five A to
five consumerZ)
consumer threads,
threads, and
and the
the result
result could
could be
be as
as shown
shown below:
below:
2.
2. There must be five consumer threads, and the result could be as shown below:

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRS

! "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRS
TUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
TUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

37
37
37
JAVA 8:MULTITHREADED PROGRAMS wait() and notify()
JAVA 8:MULTITHREADED PROGRAMS waIt() and notIFy()

EXERCISE 5
EXERCISE 5
Write a program that you can call ProducerConsumer2, and the program must again illustrate
Write a program that you can call ProducerConsumer2, and the program must again illustrate
the producer-consumer problem, but this time the class Shared must have three fields:
the producer-consumer problem, but this time the class Shared must have three fields:

1. an object of the type Buffer<Integer> – the class from exercise 3


1. an object of the type Buffer<Integer> – the class from exercise 3
2. a counter, that is an integer that counts from 1
2. a counter, that is an integer that counts from 1
3. a variable sum, that can accumulate a sum
3. a variable sum, that can accumulate a sum

In addition to get methods for the last two variables the class Shared must have two methods:
In addition to get methods for the last two variables the class Shared must have two methods:

1. a method insert(), that in the case that the buffer is not full counts the counter up
1. a method insert(), that in the case that the buffer is not full counts the counter up
by one, and inserts the value in the buffer
by one, and inserts the value in the buffer
2. a method add(), that in the case where the buffer is not empty, remove a number
2. a method add(), that in the case where the buffer is not empty, remove a number
from the buffer and adds that number to the variable sum
from the buffer and adds that number to the variable sum

The Producer class, should run in a loop, where it calls the method insert() and places the
The Producer class, should run in a loop, where it calls the method insert() and places the
numbers 1 to 1000000 (both incl.) in the buffer.
numbers 1 to 1000000 (both incl.) in the buffer.

The Consumer class should run in a loop and call the method add() that accumulates the
The Consumer class should run in a loop and call the method add() that accumulates the
sum, and it must run until there is no longer a producer.
sum, and it must run until there is no longer a producer.

Write the program so that there are 10 consumer objects and 5 producer objects, and when
Write the program so that there are 10 consumer objects and 5 producer objects, and when
the program must complete to print the accumulated sum. If the program is performed
the program must complete to print the accumulated sum. If the program is performed
correctly, the result shall be:
correctly, the result shall be:

500000500000

38
38
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS tImers
Timers

7 TIMERS
7 TIMERS
A
A timer
timer is
is an
an encapsulation
encapsulation of of aa thread,
thread, andand aa program
program can can start
start aa timer
timer that
that calls
calls aa method
method
from
from aa certain
certain time
time and
and possibly
possibly letlet the
the timer
timer call
call the
the method
method again
again after
after aa certain
certain interval.
interval.
Timers
Timers are represented by two classes. The first is the class TimerTask, which defines the
are represented by two classes. The first is the class TimerTask, which defines the
method that the timer will perform, and the other class is Timer that
method that the timer will perform, and the other class is Timer that is the timer and has is the timer and has
methods
methods to to start
start and
and terminate
terminate the the timer.
timer. The
The following
following program
program starts
starts aa timer,
timer, and
and then
then
the
the program
program prints
prints aa message
message on on thethe screen
screen every
every half
half second.
second. TheThe timer
timer is is ticking
ticking for
for 22
seconds
seconds and
and then
then itit stops
stops the
the program.
program.

package thread12;

import java.util.*;

public class Thread12


{
public static void main(String[] args)
{
TimerTask task = new TimerTask()
{

American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

▶▶ enroll by September 30th, 2014 and


▶▶ save up to 16% on the tuition!
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

39
39
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Timers
tImers
JAVA 8:MULTITHREADED PROGRAMS tImers

public void run()


public void run()
{
{ System.out.println("Alarm: The machine boils...");
System.out.println("Alarm: The machine boils...");
System.exit(0);
} System.exit(0);
}
};
};
Timer timer = new Timer();
Timer timer = new Timer();
timer.schedule(task, 2000);
timer.schedule(task, 2000);
for (;;)
for (;;)
{
{System.out.println("Hello world");
System.out.println("Hello world");
delay(500);
}delay(500);
}}
}

private static void delay(int time)


private static void delay(int time)
{
{ try
try
{
{Thread.sleep(time);
}Thread.sleep(time);
}
catch (Exception ex)
catch
{ (Exception ex)
{
}
}}
}}
}

TheTimerTask
The TimerTaskobject
objectwhich
whichdefines
definesthe
themethod
methodtotobebeperformed,
performed,isisinstantiated
instantiatedbased
basedon
on
The TimerTask
ananonymous object
anonymousclass which
classwhich defines
whichinherits the
inheritsthe method
theclass to be
classTimerTask.performed,
TimerTask.The
Theclass is instantiated
classimplements
implementsthe based
themethodon
method
an
an anonymous
run(),which class
whichisisthe which
themethod inherits
methodused
usedby the
bythe class
thetimer TimerTask.
timerthread.
thread.TheThe class
TheTimer implements
Timerobject
objecthas
hasthe the
thetype method
typeTimer,
Timer,
run(),
run(),
andthewhich
the is the
object method
starts used with
thetimer
timer by thethetimer thread. The Timer object has the type Timer,
statement
and object starts the with the statement
and the object starts the timer with the statement
timer.schedule(task, 2000);
timer.schedule(task, 2000);

whichmeans
which meansthat
thatthe
thetask
taskobject’s
object’srun()
run()method
methodmust
mustbe
becarried
carriedout
outafter
after22seconds.
seconds.IfIf
which means
youperforms that
performsthe the task
theprogram, object’s
program,the run()
theresult method
resultcould
couldbe:
be: must be carried out after 2 seconds. If
you
you performs the program, the result could be:
Hello world
Hello world
world
Hello
Hello world
world
Hello
Hello world
Hello world
Hello world
Alarm: The machine boils...
Alarm: The machine boils...

40
40
40
JAVA 8:MULTITHREADED PROGRAMS tImers
JAVA 8:MULTITHREADED PROGRAMS Timers

Below is another version of the program where the difference is that the timer is ticking
Below is another version of the program where the difference is that the timer is ticking
for the first time by half a second and then every second:
for the first time by half a second and then every second:

package thread13;

import java.util.*;

public class Thread13


{
public static void main(String[] args)
{
TimerTask task = new TimerTask()
{
public void run()
{
System.out.println("Alarm: The machine boils...");
}
};
Timer timer = new Timer();
timer.schedule(task, 500, 1000);
for (int i = 0; i < 10; ++i)
{
System.out.println("Hello world");
delay(300);
}
timer.cancel();
}

private static void delay(int time)


{
try
{
Thread.sleep(time);
}
catch (Exception ex)
{
}
}
}

Note
Note how
how to to start
start the
the timer,
timer, and
and how
how toto specify
specify the
the start
start time
time and
and the
the timer
timer interval
interval for
for
how
howoften
oftenthethetimer
timershould
shouldtick.
tick.AAtimer
timerstarts
startsaathread
threadwhich
whichby bydefault
defaultisisaanone-daemon
none-daemon
thread.
thread. The
The program
program terminates
terminates therefore,
therefore, only
only when
when thethe timer
timer isis stopped
stopped what
what happens
happens in in
the
the last
last statement
statement in in main().
main(). IfIf you
you performs
performs the
the program,
program, the the result
result could
could be:
be:

41
41
JAVA 8:MULTITHREADED PROGRAMS tImers
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS Timers
tImers

Hello world
Hello
Hello world
world
Hello
Alarm: world
The machine boils...
Alarm: The machine
Hello world boils...
Hello world
Hello world
Hello
Hello world
world
Hello
Alarm: world
The machine boils...
Alarm: The machine
Hello world boils...
Hello world
Hello world
Hello
Hello world
world
Hello
Hello world
world
Hello
Alarm: world
The machine boils...
Alarm: The machine
Hello world boils...
Hello world

A timer can also be started as a daemon thread what the program Thread14 illustrates. The
A
A timer
timer can
can also
also be
be started
started as
as aa daemon
daemon thread
thread what
what the
the program
program Thread14
Thread14 illustrates.
illustrates. The
The
only thing to do is to create the timer as follows:
only
only thing
thing to
to do
do is
is to
to create
create the
the timer
timer as
as follows:
follows:
Timer timer = new Timer(true);
Timer timer = new Timer(true);
and if you do, the last cancel() statement is unnecessary.
and if you do, the last cancel() statement is unnecessary.
and if you do, the last cancel() statement is unnecessary.

42
42
42
JAVA 8:MULTITHREADED PROGRAMS tImers

JAVA 8:MULTITHREADED
JAVA 8:MULTITHREADED PROGRAMS
PROGRAMS tImers
Timers

PROBLEM 1
PROBLEM
PROBLEM 1 you must write some classes to simulate an alarm that senses one or more
1
In this problem,
thermometers
In this
In andyou
this problem,
problem, sendmust
you messages
must writetosome
write different
some display
classes
classes devices regarding
to simulate
to simulate alarm the
an alarm
an thattemperature
that one to
senses one
senses orwhich
or more
more
the thermometers
thermometers and
thermometers shows.
and send You should
send messages
messages to solve
to different the exercise
different display according
display devices to
devices regarding the following
regarding the temperature guidelines.
temperature toto which
which
the thermometers
the thermometers shows.
shows. You
You should
should solve
solve the
the exercise
exercise according
according toto the
the following
following guidelines.
guidelines.
1) Start a new project that you can call Alarms. Add the following class to represent
a thermometer:
1) Start
1) Start aa new
new project
project that
that you
you can
can call
call Alarms.
Alarms. Add
Add the
the following
following class
class to
to represent
represent
aa thermometer:
thermometer:
public class Thermometer
{
public class Thermometer
{private static final Random rand = new Random();
private int value = rand.nextInt(10) + 15;
private static final Random rand = new Random();
private int value = rand.nextInt(10) + 15;
public Thermometer()
{
public Thermometer()
{ ...
} ...
}
public int getValue()
{
public int getValue()
{ return value;
} return value;
}}
}
The class has an int variable which represents the temperature, and it is initialized with a
The class has an int variable which represents the temperature, and it is initialized with a
random
The classvalue between
has an 15 andwhich
int variable 24 degrees.
represents the temperature, and it is initialized with a
random value between 15 and 24 degrees.
random value between 15 and 24 degrees.
You must write a constructor, so it starts a timer that ticks the first time by 1 second and
You must write a constructor, so it starts a timer that ticks the first time by 1 second and
then ticking
You must every
write second. Each
a constructor, so time thea timer
it starts timer isthat
ticking, it should
ticks the add by
first time a random
1 secondvalue
and
then ticking every second. Each time the timer is ticking, it should add a random value
between
then -5 and
ticking every10second.
to the Each
variable
timevalue. That is
the timer is, ticking,
the timer changesadd
it should thea temperature
random value–
between -5 and 10 to the variable value. That is, the timer changes the temperature –
randomly-5upand
between or down,
10 to but
the mostly
variableup.
value. That is, the timer changes the temperature –
randomly up or down, but mostly up.
randomly up or down, but mostly up.
2) Add the following interface to the project, which should define the communication
2) Add the following interface to the project, which should define the communication
2) between an alarm interface
Add the following and a display:
to the project, which should define the communication
between an alarm and a display:
between an alarm and a display:
package alarmer;
package alarmer;
public interface IDisplay
{
public interface IDisplay
{public Thermometer getThermometer();
public
public void show(int
Thermometer temp);
getThermometer();
public void warning(int temp);
public void show(int temp);
public
public void
void error();
warning(int temp);
}public void error();
}

43

43
43
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS tImers
Timers

3) As aa next
3) As next step
step you
you must
must to
to write
write aa class
class that
that can
can represent
represent aa display
display that
that can
can show
show
the temperature:
the temperature:

public class Display extends Thread implements IDisplay


{
private Termometer therm;
private String name;

public Display(String name, Termometer therm)


{
...
}

public void run()


{
...
}

public Thermometer getThermometer()


{
return term;
}

public void show(int temp)


{
System.out.println(String.format("%d degrees in %s", temp, name));
}

public void warning(int temp)


{
System.out.println(String.format("Warning: %d degrees in %s", temp, name));
}

public void error()


{
System.out.println("Disaster in " + name + " .........................");
...
}
}

44
44
JAVA 8:MULTITHREADED PROGRAMS tImers
JAVA 8:MULTITHREADED PROGRAMS Timers

A Display has a name, and shows the temperature of a particular thermometer, and both
A Display has a name, and shows the temperature of a particular thermometer, and both
the name and the thermometer is initialized in the constructor. The class will represent a
the name and the thermometer is initialized in the constructor. The class will represent a
thread and therefore it inherits the class Thread, and the class’ constructor has to start the
thread and therefore it inherits the class Thread, and the class’ constructor has to start the
thread. The run() method should in principle not do anything but just keep threads alive
thread. The run() method should in principle not do anything but just keep threads alive
in a so call busy wait (that is a loop, which performs a short sleep()). The class implements
in a so call busy wait (that is a loop, which performs a short sleep()). The class implements
the interface IDisplay and the show() method simply show the temperature, while the
the interface IDisplay and the show() method simply show the temperature, while the
method warning() must warn that the temperature is about to be critical (over 80 degrees),
method warning() must warn that the temperature is about to be critical (over 80 degrees),
and finally the method error() illustrate a disaster situation (when the temperature is 100
and finally the method error() illustrate a disaster situation (when the temperature is 100
degrees). The method error() must also terminate the thread.
degrees). The method error() must also terminate the thread.
4) You must next add a class Alarm:
4) You must next add a class Alarm:
public class Alarm
{
private ArrayList<IDisplay> observers = new ArrayList();
private Thermometer[] therms;

public Alarm(Thermometer ... therms)


{
...
}

45
45
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Timers
tImers

public void addObserver(IDisplay observer)


{
observers.add(observer);
}
}

The
Theclass
classshould
shouldhave
havetwotwovariables,
variables,the
thefirst
firstisisaacollection
collectionofofobjects
objectsofofthethetype
typeIDisplay
IDisplay
that
that will receive messages regarding the thermometers state. The class must thereforehave
will receive messages regarding the thermometers state. The class must therefore have
aamethod
methodaddObserver(),
addObserver(),which
whichcan canadd
addan anobserver
observertotothethelist.
list.The
Thesecond
secondvariable
variableisisan an
array with Thermometer objects, which are the thermometers that the
array with Thermometer objects, which are the thermometers that the alarm must monitor. alarm must monitor.
The
The constructor
constructor shall
shall initialize
initialize the
the array
array andand start
start aa timer
timer that
that isis ticking
ticking the
the first
first time
time
after 500 milliseconds, and otherwise ticks every 800 milliseconds.
after 500 milliseconds, and otherwise ticks every 800 milliseconds. Each time the timer Each time the timer
isisticking,
ticking,ititshould
shouldfor
foreach
eachthermometer
thermometersend sendmessages
messagestotothe theobservers
observersthatthatconcerning
concerning
the
the thermometer when to call error(), if the temperature is greater than or equaltoto100
thermometer when to call error(), if the temperature is greater than or equal 100
degrees and call warning() if the temperature is over 80 degrees and otherwise
degrees and call warning() if the temperature is over 80 degrees and otherwise call show(). call show().

5)5) Finally,
Finally, you
youcan
cantest
testyour
yourclasses
classeswith
withthe
thefollowing
followingmain()
main()program:
program:

package alarms;

public class Alarms


{
public static void main(String[] args)
{
Thermometer[] terms =
{ new Thermometer(), new Thermometer(), new Thermometer() };
Alarm alarm = new Alarm(terms);
alarm.addObserver(new Display("The living room", terms[0]));
alarm.addObserver(new Display("The office", terms[1]));
alarm.addObserver(new Display("The winter garden", terms[0]));
alarm.addObserver(new Display("TThe bedroom", terms[2]));
}
}

4646
JAVA 8:MULTITHREADED
JAVA 8:MULTITHREADED PROGRAMS
PROGRAMS ConCurrenCy tools
ConCurrenCy tools
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools

8 CONCURRENCY
8 CONCURRENCY TOOLS
TOOLS
Multithreaded applications
Multithreaded applications cancan generally
generally lead
lead toto concurrency
concurrency issuesissues when
when multiple
multiple threads
threads
Multithreaded applications can generally lead to concurrency issues when multiple threads
need access
need access
access toto the
to the same
the same resources,
same resources,
resources, and and where
and where the
where the order
the order
order ofof the
of the threads
the threads access
threads access
access toto the
to the resources
the resources
resources
need
plays a role.
plays aa role. This
role. This requires
This requires the
requires the threads
the threads
threads to to be
to be synchronized,
be synchronized,
synchronized, and and this
and this may
this may
may in in turn
in turn cause
turn cause other
cause other
other
plays
problems
problems as as deadlock
as deadlock
deadlock and and stavation
and stavation
stavation in in which
in which a thread
which aa thread will
thread will not
will not be
not be running,
be running,
running, sincesince it all
since itit all the
all the
the
problems
time is
time is interrupted.
interrupted. As As shown
shown in in the
the previous
previous chapter,
chapter, the
the basic
basic solution
solution is critical
critical regions
regions
time is interrupted. As shown in the previous chapter, the basic solution isis critical regions
defined with
definedwith synchronized
withsynchronized
synchronizedcode,code,
code,andand
andthe the methods
themethods wait()
methodswait()
wait()andand notify().
andnotify(). These
notify().These operations
Theseoperations
operationsare are very
arevery
very
defined
basic, and
basic, and although
and although
although in in principle
in principle is simple
principle isis simple enough,
simple enough, it’s
enough, it’s not
it’s not
not soso easy
so easy to
easy to use
to use the
use the synchronization
the synchronization
synchronization
basic,
operations
operations and and
and notnot to
not to use
to use them
use them correctly.
them correctly. Therefore,
correctly. Therefore,
Therefore, JavaJava has
Java has defined
has defined some
defined some classes,
some classes, which
classes, which
which
operations
aims to
aims to make
make it it easier
easier to
to write
write multithreaded
multithreaded applications,
applications, and and partly
partly toto make
make the the programs
programs
aims to make it easier to write multithreaded applications, and partly to make the programs
more effective.
more effective. Note
effective. Note
Note inin this
in this context
this context
context thatthat the
that the use
the use of
use of synchronized
of synchronized
synchronized on on the
on the one
the one hand
one hand ensure
hand ensure
ensure
more
critical regions,
critical regions,
regions, butbut also
but also easily
also easily lead
easily lead
lead to to programs
to programs
programs withwith poor
with poor performance,
poor performance,
performance, where where threads
where threads
threads are are
are
critical
too often
too often interrupted
often interrupted
interrupted and and have
and have
have toto wait.
to wait.
wait.
too

8.1
8.1 EXECUTORS
EXECUTORS
8.1 EXECUTORS
The concurrency
The concurrency tools tools include
include an an executor
executor asas an
an alternative
alternative to to starting
starting aa thread.
thread. It is an an
The concurrency tools include an executor as an alternative to starting a thread. ItIt isis an
object that
object that directly
that directly or
directly or indirectly
or indirectly implements
indirectly implements
implements the the interface
the interface Executor,
interface Executor,
Executor, and and the
and the purpose
purpose isis
the purpose is
object
partly
partly toto decoupling
to decoupling start
decoupling start of
start of a task
of aa task from
task from the
from the execution,
the execution,
execution, andand also
and also make
also make it more
make itit more efficient
more efficient
efficient toto
to
partly
start a thread
start aa thread and
thread and make
and make more
make more facilities
more facilities available
facilities available for
available for threads.
for threads. Here
threads. Here is a task
Here isis aa task an
task an object
an object that
object that
that
start
implements the
implements the interface
interface Runnable
Runnable or or the
the interface
interface Callable.
Callable. The
The interface
interface Executor
Executor does
does not
not
implements the interface Runnable or the interface Callable. The interface Executor does not
define all
define all the
all the desired
the desired properties
desired properties regarding
properties regarding threads,
regarding threads, and
threads, and therefore
and therefore there
there isis
therefore there defined
is defined
defined anan extended
an extended
extended
define
interface, called
interface,called ExecutorService.
calledExecutorService.
ExecutorService.The The principle
Theprinciple is that
principleisisthat you
thatyou start
youstart a thread
startaathread
threadin in the
inthe following
thefollowing
followingway:way:
way:
interface,

Executor
Executor executor
executor =
= ...;
...;
executor.execute(new
executor.execute(new RunnableTask());
RunnableTask());

The following program will partly show how to use an Executor, and partly what a Callable
The
The following
following program
program will
will partly
partly show
show how
how to
to use
use an
an Executor,
Executor, and
and partly
partly what
what aa Callable
Callable
object is:
object is:
object is:

package
package thread15;
thread15;

import java.math.*;
import java.math.*;
import
import java.util.concurrent.*;
java.util.concurrent.*;

public
public class
class Thread15
Thread15
{
{
public
public static
static void
void main(String[]
main(String[] args)
args)
{
{

47
47
47
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS Concurrency
ConCurrenCy Tools
tools

ExecutorService executor = Executors.newFixedThreadPool(2);


Callable<BigDecimal> callE = new ECalculator(200);
Callable<Long> callP = new PrimeCalculator(1000000000000000L);
Future<BigDecimal> eTask = executor.submit(callE);
Future<Long> pTask = executor.submit(callP);
try
{
while (!eTask.isDone() || !pTask.isDone())
{
System.out.println("waiting");
try
{
Thread.sleep(100);
}
catch (Exception ex)
{
}
}
System.out.println(eTask.get());
System.out.println(pTask.get());
}
catch(Exception ex)
{

Join the best at Top master’s programmes


• 3 3rd place Financial Times worldwide ranking: MSc
the Maastricht University International Business
• 1st place: MSc International Business
School of Business and • 1st place: MSc Financial Economics
• 2nd place: MSc Management of Learning

Economics! • 2nd place: MSc Economics


• 2nd place: MSc Econometrics and Operations Research
• 2nd place: MSc Global Supply Chain Management and
Change
Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012;
Financial Times Global Masters in Management ranking 2012

Maastricht
University is
the best specialist
university in the
Visit us and find out why we are the best! Netherlands
(Elsevier)
Master’s Open Day: 22 February 2014

www.mastersopenday.nl

48
48
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Concurrencytools
ConCurrenCy Tools

System.err.println(ex);
}
executor.shutdownNow();
}
}

class ECalculator implements Callable<BigDecimal>


{
private int dec;

public ECalculator(int dec)


{
this.dec = dec;
}

public BigDecimal call()


{
MathContext mc = new MathContext(dec, RoundingMode.HALF_UP);
BigDecimal y = BigDecimal.ZERO;
for (int i = 0; ; ++i)
{
BigDecimal fac = BigDecimal.ONE.divide(factorial(new BigDecimal(i)), mc);
BigDecimal z = y.add(fac, mc);
if (z.compareTo(y) == 0) break;
y = z;
}
return y;
}

private BigDecimal factorial(BigDecimal n)


{
return n.equals(BigDecimal.ZERO) ?
BigDecimal.ONE : n.multiply(factorial(n. subtract(BigDecimal.ONE)));
}
}

class PrimeCalculator implements Callable<Long>


{
private long n;

public PrimeCalculator(long n)
{
this.n = n;
}

49
49
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Concurrencytools
ConCurrenCy Tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools

public
public Long
Long call()
call()
{
{
long
long tt == n;
n;
if
if (t <= 2)
(t <= 2) return
return new
new Long(2);
Long(2);
if (t % 2 == 0)
if (t % 2 == 0) ++t;++t;
while
while (!isPrime(t))
(!isPrime(t)) t t +=
+= 2;
2;
return t;
return t;
}
}

private
private boolean
boolean isPrime(long
isPrime(long n)n)
{
{
if
if (n
(n ==
== 22 ||
|| n
n ==
== 33 ||
|| nn ==
== 55 ||
|| n
n ==
== 7)
7) return
return true;
true;
if
if (n
(n <
< 11
11 ||
|| n
n %% 2
2 ==
== 0)
0) return
return false;
false;
for
for (long
(long tt =
= 3,
3, mm =
= (long)Math.sqrt(n)
(long)Math.sqrt(n) + + 1;
1; t
t <=
<= m;
m; t
t +=
+= 2)
2)
if
if (n
(n %% t
t ==
== 0)
0) return
return false;
false;
return
return true;
true;
}
}
}
}

The
Theprogram
The programstarts
program startstwo
starts twotasks,
two tasks,performed
tasks, performedin
performed ininseparate
separatethreads
separate threadsbesacuse
threads besacuseit
besacuse ititis
isistime-consuming
time-consuming
time-consuming
operations,
operations,where
operations, wherethe
where thetwo
the twotasks
two tasksrespectively
tasks respectivelydetermines
respectively determinesaaalarge
determines largeprime
large primenumber,
prime number,and
number, andthe
and thenumber
the number
number
e.
e.e. The
The class
The class PrimeCalculator
class PrimeCalculator defines
PrimeCalculator defines aaa task
defines task as
task asas aaa Callable
Callable object
Callable object that
object that determines
that determines the
determines the first
the first
first
prime
primenumber
prime numbergreater
number greaterthan
greater thanor
than ororequal
equalto
equal totoaaaparameter
parameterpassed
parameter passedto
passed totothe
theconstructor.
the constructor.Immediately
constructor. Immediatelyaaa
Immediately
Callable
Callableclass
Callable classlooks
class lookslike
looks likeaaaRunnable
like Runnableclass,
Runnable class,and
class, andboth
and bothinterfaces
both interfacesdefines
interfaces definesaaamethod
defines method(respectively
method (respectively
(respectively
call()
call()and
call() andrun()),
and run()),which
run()), whichis
which isisthe
themethod
the methodthat
method thatis
that isisperformed
performedwhen
performed whenaaacorresponding
when correspondingobject
corresponding objectis
object isis
started
startedas
started asasaaathread,
thread,but
thread, butCallable
but Callableis
Callable isisaaageneric
genericinterface
generic interfaceand
interface andthe
and themethod
the methodcall()
method call()returns
call() returnsaaavalue
returns value
value
whose
whosetype
whose typeis
type isisthe
theparameter
the parametertype.
parameter type.This
type. Thisvalue
This valueis
value isisreturned
returnedwhen
returned whenthe
when thethread
the threadterminates.
thread terminates.The
terminates. The
The
class
class ECalculator
class ECalculator are
ECalculator are in
are inin principle
principle identical.
principle identical. The
identical. TheThe interface
interface also
interface also implements
also implements Callable
implements Callable (but
Callable (but
(but
parameterized
parameterizedwith
parameterized withanother
with anothertype).
another type).The
type). Theconstructor
The constructorhas
constructor hasaaaparameter
has parameterdec,
parameter dec,and
dec, andthe
and thecall()
the call()method
call() method
method
determines
determinesthe
determines thenumber
the numbereeewith
number withdec
with decdecimals.
dec decimals.
decimals.

Then
Then there
Then there is
there isis the
the main()
the main() program,
main() program, and
program, and the
and the first
the first thing
first thing that
thing that happens
that happens is
happens isis the
the creation
the creation of
creation ofof aaa
ExecutorService
ExecutorServiceobject.
ExecutorService object.This
object. Thisis
This isisdone
doneby
done bycalling
by callingaaastatic
calling staticmethod
static methodin
method ininthe
theclass
the classExecutors,
class Executors,which
Executors, which
which
creates
createsan
creates anExecutor
an Executorobject
Executor objectwith
object withaaathread
with threadpool
thread poolthat
pool thatcan
that canaccommodate
can accommodatetwo
accommodate twothreads.
two threads.Such
threads. Suchaaa
Such
thread
threadpool
thread poolefficiency
pool efficiencythe
efficiency thecreation
the creationof
creation ofofthreads.
threads.Then
threads. Thenon
Then onthe
on thebasis
the basisof
basis ofofthe
theabove
the aboveare
above areinstantiated
are instantiated
instantiated
two
twoCallable
two Callableobjects,
Callable objects,that
objects, thatstarts
that startstwo
starts twothreads,
two threads,for
threads, forexample
for example
example

Future<BigDecimal>
Future<BigDecimal> eTask
eTask =
= executor.submit(callE);
executor.submit(callE);

Here youshould
Here should notethe
the typeFuture
Future thatisisaageneric
generic interface,and
and inthis
this casean
an eTask
Here you
you should note
note the type
type Future that
that is a generic interface,
interface, and inin this case
case an eTask
eTask
objectthat
object thatcan
canbe
beused
usedtotorefer
refertotothe
thethread’s
thread’sreturn
returnvalue.
value.InInthis
thiscase,
case,the
theprimary
primarythread
thread
object that can be used to refer to the thread’s return value. In this case, the primary thread
performes a busywait
performes wait untilboth
both threadsterminates,
terminates, afterwhich
which theresults
results areprinted.
printed.
performes aa busy
busy wait until
until both threads
threads terminates, after
after which the
the results are
are printed.

50
50
50
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools

You should note the last statement in main(), which close the Executor. It is necessary, otherwise
You should note the last statement in main(), which close the Executor. It is necessary, otherwise
there will be registered a none-daemon thread, and the program will then not terminate.
there will be registered a none-daemon thread, and the program will then not terminate.

EXERCISE 6
EXERCISE 6
Create a project that you can call Calculations. Copy the two classes ECalulator and
Create a project that you can call Calculations. Copy the two classes ECalulator and
PrimeCalculator to the project. You must change the two classes so
PrimeCalculator to the project. You must change the two classes so

1. instead of Callable they implements the interface Runnablede


1. instead of Callable they implements the interface Runnablede
2. they do not return a value, but instead prints the results on screen
2. they do not return a value, but instead prints the results on screen

You must then add a class:


You must then add a class:

class SqrtCalculator implements Runnable


{
private BigDecimal x;
private int dec;

51
51
JAVA
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
8:MULTITHREADED PROGRAMS
PROGRAMS ConCurrenCy
Concurrencytools
ConCurrenCy Tools
tools

public
public SqrtCalculator(BigDecimal
SqrtCalculator(BigDecimal x,x, int
int dec)
dec) throws
throws IllegalArgumentException
IllegalArgumentException
{
{
if
if (x.signum()
(x.signum() < < 0)
0) throw
throw new
new IllegalArgumentException(
IllegalArgumentException(
"sqrt():
"sqrt(): The argument must be
The argument must be none-negative");
none-negative");
this.x = x;
this.x = x;
this.dec
this.dec == dec;
dec;
}
}

public
public void
void run()
run()
{
{
}
}
}
}

where
where the run() method should print the square root of x.
wherethe
therun()
run()method
methodshould
shouldprint
printthe
thesquare
squareroot
rootofofx.x.

Finally,
Finally, write the following main() method:
Finally,write
writethe
thefollowing
followingmain()
main()method:
method:
public
public static
static void
void main(String[]
main(String[] args)
args)
{
{
//
// creates
creates an
an ExecutorService
ExecutorService object
object with
with room
room for
for 5
5 running
running threads
threads

//
// loop
loop that
that submits
submits 100
100 runnable
runnable objects
objects to
to the
the executor
executor object
object
//
// when there for every iteration randomly are instantiated an
when there for every iteration randomly are instantiated an
//
// object
object of
of the
the classes
classes ECalculator,
ECalculator, PrimeCalculator
PrimeCalculator and
and SqrtCalculator
SqrtCalculator
for
for (int
(int i
i == 0;
0; ii <
< 100;
100; ++i)
++i)
{
{
}
}

//
// the
the primary
primary thread
thread has
has to
to wait
wait so
so long
long that
that all
all threads
threads are
are executed
executed

//
// termnates
termnates the
the executor
executor object
object
}
}

When
When you are done, you may experimenting in terms of how many threads that can
When you
you are
are done,
done, you
you may
may experimenting
experimenting inin terms
terms ofof how
how many
many threads
threads that
that can
can
simultaneously
simultaneously run and how many tasks the loop submits.
simultaneouslyrun
runand
andhow
howmany
manytasks
tasksthe
theloop
loopsubmits.
submits.

8.2
8.2 COUNTDOWNLATCH
COUNTDOWNLATCH
8.2 COUNTDOWNLATCH
A
AACountDownLatch
CountDownLatch is a synchronization object, which allows one or more threads to wait
CountDownLatchisisaasynchronization
synchronizationobject,
object,which
whichallows
allowsone
oneorormore
morethreads
threadstotowait
wait
at
atataaa“gate”
“gate” until
until another
another thread
thread opens
opens the
the gate,
gate, after
after which
which the
the waiting
waiting threads
threads can
can proceed.
proceed.
“gate” until another thread opens the gate, after which the waiting threads can proceed.
A CountDownLathch
A CountDownLathch is is primary aa counter
counter and hashas operations, where
where a thread waits
waits until
A CountDownLathch isprimary primary a counterand and hasoperations,
operations, whereaathread
thread waitsuntil
until
the
the counter is counting down to the 0.
thecounter
counterisiscounting
countingdown
downtotothe
the0.0.

5252
52
JAVA 8:MULTITHREADED
JAVA 8:MULTITHREADED PROGRAMS
PROGRAMS Concurrency tools
ConCurrenCy Tools

Thefollowing
The followingprogram
programwill
willshow
showhow
howto
toapply
applyaaCountDownLatch
CountDownLatchto tosynchronization
synchronizationof ofobjects.
objects.
The program
The program starts
starts N
N worker
worker threads,
threads, that
that are
are unable
unable to
to continue
continue untiluntil aa CountDownLatch
CountDownLatch
isis countdown.
countdown. After
After the
the primary
primary thread
thread has
has done
done aa work,
work, itit isis blocked
blocked until
until each
each worker
worker
thread has
thread has counted
counted down
down the
the CountDownLatch.
CountDownLatch. This This means
means that
that thethe primary
primary thread
thread waits
waits
for all
for all worker
worker threads
threads to
to terminate.
terminate.

package thread16;

import java.util.*;
import java.util.concurrent.*;

public class Thread16


{
private final static int N = 5;

public static void main(String[] args)


{
final CountDownLatch startLatch = new CountDownLatch(1);
final CountDownLatch doneLatch = new CountDownLatch(N);
Runnable worker = new Worker(startLatch, doneLatch);
ExecutorService executor = Executors.newFixedThreadPool(N);
for (int i = 0; i < N; ++i) executor.execute(worker);
try
{
System.out.println("Main working");
Thread.sleep(1000);
startLatch.countDown();
System.out.println("Main doing work");
doneLatch.await();
executor.shutdownNow();
}
catch (InterruptedException ex)
{
System.err.println(ex);
}
}
}

class Worker implements Runnable


{
private static final Random rand = new Random();
private final CountDownLatch start;
private final CountDownLatch done;

53
53
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools

public Worker(CountDownLatch start, CountDownLatch done)


{
this.start = start;
this.done = done;
}

public void run()


{
try
{
print("Entered run()");
start.await();
print("Working");
Thread.sleep(rand.nextInt(1000));
done.countDown();
}
catch (InterruptedException ex)
{
System.err.println(ex);
}
}

Need help with your


dissertation?
Get in-depth feedback & advice from experts in your
topic area. Find out what you can do to improve
the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

54
54
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS ConCurrenCy
ConCurrenCy tools
tools

void
void print(String
print(String text)
text)
{
{
System.out.println("[" +
System.out.println("[" Thread.currentThread().getId() +
+ Thread.currentThread().getId() "] "
+ "] " +
+ text);
text);
}
}
}
}

The
The class
class Worker
Worker defines
defines aa runnable
runnable object
object (a(a task)
task) to
to simulate
simulate that
that work
work isis carried
carried out
out onon
the machine.
the machine.
the machine. An An object
An object isis initialized
object is initialized with
initialized with two
with two CountDownLatch
two CountDownLatch objects.
CountDownLatch objects. The
objects. The run()
The run() method
run() method
method
starts
starts to
to print
print aa message
message thatthat the
the threads
threads are
are started,
started, but
but then
then block
block itself
itself (at
(at the
the gate):
gate):

start.await();
start.await();

and
and waiting
waiting for for another
another thread
thread to
to signal
signal that
that itit must
must continue.
continue. WhenWhen that
that happens,
happens, the the
thread
threadprints
printsagainagainaatext textand
andperforms
performsaasleep()
sleep()(to(toillustrate
illustratethat
thatthe
thethread
threaddo
dosomething),
something),
and when
and when
and when ititit is
isis finished
finished the
finished the second
the second synchronization
second synchronization object
synchronization object isis counting
object is counting down
counting down so
down so itit knows
so it knows
knows
when
when all
all threads
threads are are finished.
finished.

main()
main() defines
defines two
two synchronization
synchronization objects:
objects:

final CountDownLatch startLatch = new CountDownLatch(1);


final CountDownLatch startLatch = new CountDownLatch(1);
final CountDownLatch doneLatch = new CountDownLatch(N);
final CountDownLatch doneLatch = new CountDownLatch(N);

where
where the
the first
first should
should bebe used
used to
to block
block thethe start
start of
of the
the N
N worker
worker threads
threads until
until the
the primary
primary
thread
thread opens
opens up up and
and allows
allows the
the threads
threads to to continue.
continue. The The second
second should
should be be used
used to
to get
get the
the
primary thread
primary thread
primary thread to to wait
to wait until
wait until all
until all worker
all worker threads
worker threads are
threads are completed.
are completed.
completed. Next Next isis created
Next is created
created aaa runnable
runnable
runnable
object
object toto aa worker
worker thread,
thread, and
and there
there isis created
created anan Executor
Executor object
object for
for N N threads.
threads. The
The next
next
loop
loop adds
adds N N threads
threads to to the
the executor
executor object.
object. Note
Note thatthat the
the threads
threads are
are started
started onon basis
basis of
of
the
the same
same object.
object. TheThe threads
threads start
start immediately,
immediately, but but when
when theythey blocks
blocks themself,
themself, andand there
there
isis no
is no momentum
no momentum
momentum prior prior to
prior to the
to the primary
the primary thread
primary thread opens
thread opens up.
opens up. ItIt first
up. It first performs
performs aaa work
first performs work and
work and then
and then
then
opens
opens thethe gate
gate (the
(the synchronization
synchronization objectobject startLatch
startLatch isis counted
counted down),
down), and and the
the worker
worker
threads
threads can
can proceed.
proceed. The The primary
primary thread
thread alsoalso continues
continues and and performs
performs

doneLatch.await();
doneLatch.await();

This means that the primary thread is blocked waiting until the worker threads have counted
This means that the primary thread is blocked waiting until the worker threads have counted
the synchronization
the synchronization object
object down
down to
to 0.
0.
the synchronization object down to 0.

55
55
55
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools

EXERCISE
EXERCISE 77
Start
Start by
by creating
creating aa copy
copy of
of the
the project
project Calculations
Calculations (Exercise
(Exercise 6),
6), and
and calls
calls for
for example
example the
the
copy for Calculations1. Open the copy in NetBeans. The solution has a
copy for Calculations1. Open the copy in NetBeans. The solution has a problem as the problem as the
primary
primary thread
thread waits
waits toto all
all the
the worker
worker threads
threads are
are finish
finish by
by waiting
waiting long
long enough.
enough. Solve
Solve this
this
problem by using a CountDownLatch.
problem by using a CountDownLatch.

8.3 CYCLICBARRIER
8.3 CYCLICBARRIER
AA CyclicBarrier
CyclicBarrier isis aa synchronization
synchronization object
object which
which can
can be
be used
used to
to ensure
ensure that
that multiple
multiple threads
threads
are
are waiting on each other at a certain barrier point. The object is cyclic, since it can
waiting on each other at a certain barrier point. The object is cyclic, since it can be
be
recycled
recycled after having released waiting threads. The synchronization mechanism is useful if aa
after having released waiting threads. The synchronization mechanism is useful if
program
program that
that starts
starts aa certain
certain number
number of of threads
threads which
which must
must wait
wait for
for each
each other.
other. Sometimes
Sometimes
you
you can think of it as multiple threads are performing work on a common problem, and
can think of it as multiple threads are performing work on a common problem, and
that the task is first solved when all the threads have completed their
that the task is first solved when all the threads have completed their work. work.

The
The following
following program
program creates
creates and
and initalizes
initalizes aa square
square matrix.
matrix. Next,
Next, the
the application
application determine
determine
the
the square root of each of the matrix’s items, but it must take place in that way, that starting
square root of each of the matrix’s items, but it must take place in that way, that starting
aa thread for each row, wherein the thread is processing that row. The result is
thread for each row, wherein the thread is processing that row. The result is only available only available
when
when all
all threads
threads have
have finished
finished their
their work,
work, after
after which
which the
the individual
individual threads
threads work
work in
in principle
principle
are
are merges into a finished result. It obviously can not be made until the individual threads
merges into a finished result. It obviously can not be made until the individual threads
are completed and it can be synchronized with a
are completed and it can be synchronized with a CyclicBarrier. CyclicBarrier.

package thread17;

import java.util.concurrent.*;

public class Thread17


{
private static final int N = 5; // the size of the matrix

public static void main(String[] args)


{
float[][] matrix = create();
print(matrix);
System.out.println();
Solver solver = new Solver(matrix);
System.out.println();
print(matrix);
}

56
56
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Concurrencytools
ConCurrenCy Tools

private static float[][] create()


{
float[][] matrix = new float[N][N];
for (int r = 0, n = 0; r < matrix.length; ++r)
for (int c = 0; c < matrix[r].length; ++c) matrix[r][c] = ++n;
return matrix;
}

private static void print(float[][] matrix)


{
for (int r = 0; r < matrix.length; ++r)
{
for (int c = 0; c < matrix[r].length; ++c) System.
out.printf("%10.4f", matrix[r][c]);
System.out.println();
}
}
}

class Solver
{
private final float[][] data; // matricen
private final CyclicBarrier barrier; // synkroniserer flere trådes arbejde

Brain power By 2020, wind could provide one-tenth of our planet’s


electricity needs. Already today, SKF’s innovative know-
how is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

57
57
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS Concurrency
ConCurrenCy Tools
tools

public Solver(float[][] matrix)


{
data = matrix;
barrier =
new CyclicBarrier(matrix.length, new Runnable()
{ public void run() { merge(); } });
for (int r = 0; r < matrix.length; ++r) new Thread(new Worker(r)).start();
synchronized("abc")
{
try
{
System.out.println("[" +Thread.currentThread().getId() + "] waiting");
"abc".wait();
System.out.println("[" +Thread.currentThread().getId() + "] notified");
}
catch (InterruptedException ie)
{
System.out.println("main thread interrupted");
}
}
}

void merge()
{
System.out.println("merging");
synchronized("abc")
{
"abc".notify();
}
}

class Worker implements Runnable


{
private final int row; // the row that the thread works on
private boolean done = false; // when the thread has to stop

public Worker(int row)


{
this.row = row;
}

public boolean done()


{
return done;
}

58
58
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS ConCurrenCy
ConCurrenCy tools
tools

private
private void
void work()
work()
{{
System.out.println("Behandler
System.out.println("Behandler række:
række: "" ++ row);
row);
for
for (int
(int ii == 0;
0; ii << data[row].length;
data[row].length; ++i)
++i)
data[row][i] = (float)Math.sqrt(data[row][i]);
data[row][i] = (float)Math.sqrt(data[row][i]);
done
done == true;
true;
}}

public
public voidvoid run()
run()
{{
while
while (!done())
{{
work();
work();
try
try
{{
barrier.await();
barrier.await();
}}
catch
catch (Exception
(Exception ex)
ex)
{{
return;
return;
}}
}}
}}
}}
}}

Themethod
The methodcreate()
create()creates
createsthe thematrix
matrixand andthe themethod
methodprint()
print()prints
printsthethematrix
matrixon onthe
the
screen.Both
screen. Bothofofthese
thesemethods
methodsare aretrivial.
trivial.After
Afterthe
thematrix
matrixhashasbeen
beencreated,
created,isisinstantiated
instantiated
ananobject
objectofofthe
thetype
typeSolver,
Solver,andandititisisthe
theobject
objectwhich
whichsolves
solvesthe
theproblem.
problem.The Theclass
classSolver
Solver
createsaaCyclicBarrier
creates CyclicBarrierwhich
whichisisinitialized
initializedwith
withaanumber
numberofofworker
workerthreads,
threads,andandaarunnable
runnable
objecttotobe
object beperformed
performedwhen whenall allworker
workerthreads
threadshavehavecompleted
completedtheirtheirwork.
work.InInthis
thiscase,
case,the
the
object’srun()
object’s run()method
methodcallscallsthe
themethod
methodmerge().
merge().After
Afterthe
theworker
workerthreads
threadsarearecreated
created––one one
threadfor
thread foreach
eachrow
row––and andthethethreads
threadsarearecreated
createdononbasis
basisofofaarunnable
runnableobject
objectofofthethetype
type
Worker.The
Worker. Theclass
classisisbasically
basicallytrivial,
trivial,but
butititisisan
aninner
innerclass
class(in
(inthe
theclass
classSolver)
Solver)and
andtherefore
therefore
ititknows
knowsthe thesynchronization
synchronizationobject objectbarrier,
barrier,andandafter
afteritithas
hasdone
doneitsitsjob,
job,ititperforms
performsaa

barrier.await();
barrier.await();

whichmeans
which meansthat
thatthe
thethread
threadisiswaiting
waitingatatthe
thebarrier.
barrier.After
Afterthe
theconstructor
constructorininthe
theclass
classSolver
Solver
hasstarted
has startedthe
theworker
workerthreads,
threads,ititperforms
performswait()
wait()ononaalock
lock(which
(whichisissimply
simplyaastring),
string),and
and
ititmeans
meansthat
thatthe
theprimary
primarythread
threadwaits
waitsuntil
untilititgets
getsaanotify
notifyfrom
fromanother
anotherthread.
thread.

59
59
59
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy
Concurrency tools
Tools

After all worker threads are performed an await() on the barrier (all threads have reached
the barrier), the barrier object let the threads continue (which here simply means that
they stop) and carry out its own thread, which here calls the merge() method. It does not
much, but it sends a notify() on the lock set by the primary thread, and the result is that
the primary thread continues.

If you executes the program, you get the result:

1,0000 2,0000 3,0000 4,0000 5,0000


6,0000 7,0000 8,0000 9,0000 10,0000
11,0000 12,0000 13,0000 14,0000 15,0000
16,0000 17,0000 18,0000 19,0000 20,0000
21,0000 22,0000 23,0000 24,0000 25,0000

Behandler række: 0
Behandler række: 1
Behandler række: 2
Behandler række: 3
[1] waiting
Behandler række: 4
merging
[1] notified

60
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA 8:MULTITHREADED
JAVA 8:MULTITHREADED PROGRAMS
PROGRAMS ConCurrenCy
ConCurrenCy toolstools

1,0000
1,0000 1,4142
1,4142 1,7321
1,7321 2,0000
2,0000 2,2361
2,2361
2,4495
2,4495 2,6458
2,6458 2,8284
2,8284 3,0000
3,0000 3,1623
3,1623
3,3166
3,3166 3,4641
3,4641 3,6056
3,6056 3,7417
3,7417 3,8730
3,8730
4,0000
4,0000 4,1231
4,1231 4,2426
4,2426 4,3589
4,3589 4,4721
4,4721
4,5826
4,5826 4,6904
4,6904 4,7958
4,7958 4,8990
4,8990 5,0000
5,0000

PROBLEM
PROBLEM 2
PROBLEM 22
CreateCreate
a newaaproject,
Create new
new project,
that you
project, that you
thatcan can
youcall
can call
call Calculations2.
Calculations2. Add
Add the
Calculations2. Add the
the following
following class
class which
class which
following has a has
which has aa
static static
staticmethod
method that
thatcreates
that creates
method aarandom
a random
creates BigDecimal
BigDecimal
random with
with 100
BigDecimal 100
100digits
withdigits digitsbefore
before and
and after
before after
andthe the
thedecimal
decimal
after decimal
point,point,
as as
well well
as a as a
static static
method, method,
which which determines
determines the the
square square
root root
of a of a BigDecimal:
BigDecimal:
point, as well as a static method, which determines the square root of a BigDecimal:

abstract
abstract classclass
Calc Calc
{ {
private static final int N = 100;
private static final int N = 100;
public static final Random rand = new Random();
public static final Random rand = new Random();
public static final MathContext context =
public static final MathContext context =
new MathContext(N,
new MathContext(N, RoundingMode.HALF_UP);
RoundingMode.HALF_UP);

publicpublic static
static BigDecimal
BigDecimal random()
random()
{ {
StringBuilder
StringBuilder builder
builder = new= StringBuilder();
new StringBuilder();
builder.append((char)('1'
builder.append((char)('1' + rand.nextInt(9)));
+ rand.nextInt(9)));
for (int
for (int ii
i = 0; =<0;N;
i ++i)
< N; ++i) builder.append((char)('0'
builder.append((char)('0' + rand.nextInt(10)));
+ rand.nextInt(10)));
builder.append('.');
builder.append('.');
for (int
for (int ii
i = 0; =<0;N;
i ++i)
< N; ++i) builder.append((char)('0'
builder.append((char)('0' + rand.nextInt(10)));
+ rand.nextInt(10)));
returnreturn new BigDecimal(builder.toString());
new BigDecimal(builder.toString());
} }

public public
staticstatic BigDecimal
BigDecimal sqrt(BigDecimal
sqrt(BigDecimal x) x)
{ {
BigDecimal value = BigDecimal.ZERO;
BigDecimal value = BigDecimal.ZERO;
if (x.signum()
if (x.signum() != 0)!= 0)
{ {
BigInteger
BigInteger t = x.movePointRight(N
t = x.movePointRight(N << 1).toBigInteger();
<< 1).toBigInteger();
BigInteger
BigInteger y = t.shiftRight((t.bitLength()
y = t.shiftRight((t.bitLength() + 1) +>>1)1);
>> 1);
for (BigInteger
for (BigInteger z = zy;;
z = y;; z = y)
= y)
{ {
y = y.add(t.divide(y)).shiftRight(1);
y = y.add(t.divide(y)).shiftRight(1);
if (y.compareTo(z)
if (y.compareTo(z) == 0)==break;
0) break;
} }
valuevalue= new= BigDecimal(y,
new BigDecimal(y,
N); N);
} }
return return value;
value;
} }
} }

61
61 61
JAVA 8:MULTITHREADED PROGRAMS
JAVA PROGRAMS Concurrency Tools
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS ConCurrenCy
ConCurrenCy tools
tools

You do
You
You do not
do not have
not have to
have to study
to study the
study the code
the code when
code when the
when the only
the only goal
only goal is
goal isis that
that the
that the method
the method sqrt()
method sqrt() that
sqrt() that takes
that takes
takes
aaa long
long time.
long time.
time.

Add aaa method


Add
Add method to
method to the
to the main
the main class,
main class, which
class, which creates
which creates an
creates an array
an array of
array of n
of nn objects
objects of
objects of type
of type BigDecimal
type BigDecimal
BigDecimal
when the
when
when the objects
the objects must
objects must be
must be created
be created with
created with the
with the method
the method Calc.random():
method Calc.random():
Calc.random():

private
private static
static BigDecimal[]
BigDecimal[] create(int
create(int n)
n)
{
{
}
}

The program
The
The program should
program should now
should now use
now use this
use this method
this method to
method to create
to create an
create an array
an array of
array of the
of the type
the type BigDecimal
type BigDecimal with
BigDecimal with
with
10 numbers,
10
10 numbers, and
numbers, and then
and then the
then the program
the program must
program must print
must print the
print the result
the result of
result of method
of method
method

private
private static
static BigDecimal
BigDecimal sum1(BigDecimal[]
sum1(BigDecimal[] tal)
tal)
{
{
}
}

when the
when
when the method
the method must
method must return
must return the
return the sum
the sum of
sum of the
of the square
the square roots
square roots of
roots of the
of the numbers
the numbers in
numbers in the
in the array.
the array.
array.
The method
The
The method must
method must also
must also print
also print the
print the time
the time of
time of the
of the calculation
the calculation measured
calculation measured in
measured in nanoseconds.
in nanoseconds. You
nanoseconds. You can
You can
can
read the
read
read the hardware
the hardware clock
hardware clock with:
clock with:
with:

System.nanoTime()
System.nanoTime()

When
When the method sum1() works, write aa similar method sum2(), but it must instead works
When thethe method
method sum1()
sum1() works,
works, write
write a similar
similar method
method sum2(),
sum2(), but
but itit must
must instead
instead works
works
that
that way,
way, that
that it
it starts
starts aa worker
worker thread
thread to
to calculate
calculate each
each square
square root.
root. It
It can
can only
only calculate
calculate
that way, that it starts a worker thread to calculate each square root. It can only calculate
the
the sum, and after all threads have calculated the square roots, you need to synchronize the
the sum,
sum, and
and after
after all
all threads
threads have
have calculated
calculated the
the square
square roots,
roots, you
you need
need to to synchronize
synchronize the
the
threads
threads using
using aa CyclicBarrier.
CyclicBarrier.
threads using a CyclicBarrier.

Examine
Examine which of the two methods that have the best performance. Also explore what
Examine which
which ofof the
the two
two methods
methods that
that have
have the
the best
best performance.
performance. Also
Also explore
explore what
what
happens
happens if
if you
you change
change the
the number
number of
of digits
digits in
in the
the class
class Calc
Calc (the
(the constant
constant N
N ).
). Also
Also check
check
happens if you change the number of digits in the class Calc (the constant N ). Also check
what
what happens if you change the number of threads and thus the size of the array.
what happens
happens ifif you
you change
change the
the number
number ofof threads
threads and
and thus
thus the
the size
size of
of the
the array.
array.

8.4
8.4 EXCHANGER
EXCHANGER
8.4 EXCHANGER
An
An Exchanger provides a synchronization point at which threads can exchange objects.
An Exchanger
Exchanger provides
provides aa synchronization
synchronization point point at
at which
which threads
threads can can exchange
exchange objects.
objects.
That
That is, that aa thread can call an exchange() methode and wait for another thread to do
That is, that a thread can call an exchange() methode and wait for another thread to
is, that thread can call an exchange() methode and wait for another thread to do
do
the
the same,
same, and
and then
then the
the threads
threads can
can switch
switch two
two objects.
objects. Maybe
Maybe it’s
it’s not
not the
the most
most commonly
commonly
the same, and then the threads can switch two objects. Maybe it’s not the most commonly
used
used synchronization object, but it has its uses in connection with the implementation
used synchronization
synchronization object,
object, but
but itit has
has its
its uses
uses in
in connection
connection with with thethe implementation
implementation
of
of specific algorithms. The following program shows how to use an Exchanger, where two
of specific algorithms. The following program shows how to use an Exchanger, where
specific algorithms. The following program shows how to use an Exchanger, where two
two
threads
threads swap
swap two
two objects
objects of
of the
the type
type Buffer.
Buffer. The
The class
class Buffer
Buffer is
is the
the same
same class
class that
that is
is used
used
threads swap two objects of the type Buffer. The class Buffer is the same class that is used
in
in some of the above exercises.
in some
some of of the
the above
above exercises.
exercises.

62
62
62
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Concurrency
ConCurrenCy Tools
tools

package thread18;

import java.util.*;
import java.util.concurrent.*;

public class Thread18


{
private static final Random rand = new Random();
private final static Exchanger<Buffer<Character>> exchanger = new Exchanger();
private final static Buffer<Character> buffer1 = new Buffer(15);
private final static Buffer<Character> buffer2 = new Buffer(10);
private static char ch = 'Z';

public static void main(String[] args)


{
class Producer implements Runnable
{
public void run()
{
Buffer<Character> buffer = buffer1;
try
{
while (true)
{

63
63
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Concurrencytools
ConCurrenCy Tools

buffer.insert(next());
Thread.sleep(rand.nextInt(500));
if (buffer.full()) buffer = exchanger.exchange(buffer);
}
}
catch (Exception ex)
{
System.out.println(ex);
}
}
}

class Consumer implements Runnable


{
public void run()
{
Buffer<Character> buffer = buffer2;
try
{
while (true)
{
Thread.sleep(rand.nextInt(500));
if (buffer.empty())
{
buffer = exchanger.exchange(buffer);
System.out.println();
}
System.out.print(buffer.remove());
}
}
catch (Exception ex)
{
System.out.println(ex);
}
}
}
new Thread(new Producer()).start();
new Thread(new Consumer()).start();
}

private static char next()


{
if (ch == 'Z') ch = 'A'; else ++ch;
return ch;
}
}

64
64
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools

8.5 SEMAPHORE
8.5 SEMAPHORE
A semaphore manages a number of permits in relation to a number of threads that want to
A semaphore manages a number of permits in relation to a number of threads that want to
access a shared resource. A thread that is trying to obtain permission for the resource, while
access a shared resource. A thread that is trying to obtain permission for the resource, while
all licenses are used, is blocked until another thread releases the license. A semaphore’s value
all licenses are used, is blocked until another thread releases the license. A semaphore’s value
is an integer whose value is not negative and can be counted up or down. If the semaphore
is an integer whose value is not negative and can be counted up or down. If the semaphore
can take only the values 0 and 1, we speak of a binary semaphore, and may the value be
can take only the values 0 and 1, we speak of a binary semaphore, and may the value be
greater than 1, it is called a counting semaphore. This means that is the access to a resource
greater than 1, it is called a counting semaphore. This means that is the access to a resource
controlled with a counting semaphore, there are several threads at a time (determined by
controlled with a counting semaphore, there are several threads at a time (determined by
semaphoren) that can access the resource. The following program will show how to use
semaphoren) that can access the resource. The following program will show how to use
a semaphore:
a semaphore:
package thread19;

import java.util.*;
import java.util.concurrent.*;

public class Thread19


{
public static void main(String[] args)
{
final Resources resources = new Resources();
Worker worker = new Worker(resources);
int N = 2 * Resources.N;
ExecutorService executor = Executors.newFixedThreadPool(N);
for (int i = 0; i < N; ++i) executor.execute(worker);
try
{
executor.awaitTermination(20, TimeUnit.SECONDS);
}
catch (Exception ex)
{
}
executor.shutdownNow();
}
}

class Worker implements Runnable


{
private static final Random rand = new Random();
private Resources resources;
private long counter = 0;

65
65
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS Concurrency
ConCurrenCy toolsTools

public Worker(Resources resources)


{
this.resources = resources;
}

public void run()


{
try
{
while (counter < 100)
{
Resource res = resources.getResouce();
System.out.printf("[%d] anvender %s: %3d\n",
Thread.currentThread().getId(), res.toString(), res.getValue());
Thread.sleep(500 + rand.nextInt(500));
res.updateValue(++counter);
resources.putResource(res);
System.out.printf("[%d] opdateret %s: %3d\n",
Thread.currentThread().getId(), res.toString(), res.getValue());
Thread.sleep(500 + rand.nextInt(500));
}
}
catch (InterruptedException ex)
{

Challenge the way we run

EXPERIENCE THE POWER OF


FULL ENGAGEMENT…

RUN FASTER.
RUN LONGER.. READ MORE & PRE-ORDER TODAY
RUN EASIER… WWW.GAITEYE.COM

1349906_A6_4+0.indd 1 66 22-08-2014 12:56:57

66
JAVA 8:MULTITHREADED
JAVA 8:MULTITHREADED PROGRAMS
PROGRAMS Concurrency tools
ConCurrenCy Tools

System.out.println(ex);
}
}
}

class Resources
{
public static final int N = 10; // number of Resource objects
private final Resource[] resources = new Resource[N];
private final Semaphore sema = new Semaphore(N, true);
private final boolean[] used = new boolean[N];

public Resources()
{
for (int i = 0; i < resources.length; ++i) resources[i] = new Resource();
}

public Resource getResouce() throws InterruptedException


{
sema.acquire();
return get();
}

public void putResource(Resource res)


{
if (unused(res)) sema.release();
}

private synchronized Resource get()


{
for (int i = 0; i < N; ++i)
{
if (!used[i])
{
used[i] = true;
return resources[i];
}
}
return null;
}

private synchronized boolean unused(Resource res)


{
for (int i = 0; i < N; ++i)
{
if (res.equals(resources[i]))
{

67
67
JAVA 8:MULTITHREADED
JAVA 8:MULTITHREADED PROGRAMS
PROGRAMS Concurrency tools
ConCurrenCy Tools

if (used[i])
{
used[i] = false;
return true;
}
else return false;
}
}
return false;
}
}

class Resource
{
private static int ID = 0;
private int id; // the ressource's id
private long value; // the ressource's value

public Resource()
{
id = ++ID;
}

public long getValue()


{
return value;
}

public void updateValue(long value)


{
this.value += value;
}

public boolean equals(Object obj)


{
if (obj == null) return false;
if (getClass() == obj.getClass()) return ((Resource)obj).id == id;
return false;
}

public String toString()


{
return String.format("Resource: [%d]", id);
}
}

68
68
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools

The class Resource is a simple encapsulation of a long and has basically two methods:
The class Resource is a simple encapsulation of a long and has basically two methods:

1. getValue() that returns the object’s value


1. getValue() that returns the object’s value
2. updateValue(), that adds a value to the object’s value
2. updateValue(), that adds a value to the object’s value

Each object is assigned also a consecutively number when it is created, and it is only to
Each object is assigned also a consecutively number when it is created, and it is only to
have an identification of the object and to give the object a name in toString().
have an identification of the object and to give the object a name in toString().

The most importannt class is the class Resources, which is an encapsulation of an array of
The most importannt class is the class Resources, which is an encapsulation of an array of
Resource objects. The idea is that a thread may wish to get a Resource object and update it.
Resource objects. The idea is that a thread may wish to get a Resource object and update it.
While this happens, the object is locked and is released again after it is updated. The class
While this happens, the object is locked and is released again after it is updated. The class
creates a Semaphore to check the threads access to an object:
creates a Semaphore to check the threads access to an object:

private final Semaphore sema = new Semaphore(N, true);

This e-book
is made with SETASIGN
SetaPDF

PDF components for PHP developers

www.setasign.com

69
69
JAVA
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
8:MULTITHREADED PROGRAMS
PROGRAMS ConCurrenCy
Concurrencytools
ConCurrenCy Tools
tools

ItItis
It isisaaacounting
counting semaphore,
countingsemaphore,
semaphore,and and the
andthe first
thefirst parameter
firstparameter indicates
parameterindicates the
indicatesthe number
thenumber
numberof ofofthreads
threads which
threadswhich
which
can
cansimultaneously
can simultaneouslyuse
simultaneously usean
use ananobject
objectof
object ofofthe
thetype
the typeResources.
type Resources.This
Resources. Thiscorresponds
This correspondsto
corresponds totothe
thearray
the arraylength,
array length,
length,
since
sinceit
since ititis
isisthe
thenumber
the numberof
number ofofResource
Resourceobjects
Resource objectsthat
objects thatare
that areavailable.
are available.The
available. Thelast
The lastparameter
last parameterensures
parameter ensuresthat
ensures that
that
threads
threads are
threads are blocked
are blocked on
blocked on this
on this semaphore,
this semaphore, not
semaphore, not being
not being starved
being starved and
starved and never
and never get
never get running
get running again.
running again.
again.
When creating
Whencreating
When creatingaaaResources
Resources object
Resourcesobject
objectisisisthe
the semaphore’s
thesemaphore’s value
semaphore’svalue N,
valueN, and
N,and thus
andthus there
thusthere
thereareare NNthreads
areN threads
threads
that
thatcan
that canuse
can usethe
use theobject.
the object.The
object. Theclass
The classalso
class alsohas
also hasan
has anarray
an arrayof
array ofoftype
typeboolean,
type boolean,and
boolean, andit
and ititis
isisused
usedto
used totocontrol
control
control
which
whichResource
which Resourceobjects
Resource objectsthat
objects thatare
that arein
are ininuse.
use.
use.

The class
The class
The has
class has two
has two public
two public methods:
public methods: getResource()
methods: getResource() and
getResource() and putResource().
and putResource(). The
putResource(). The first
The first returns
first returns an
returns an
an
available
availableResource
available Resourceobject,
Resource object,and
object, andit
and ititstarts
startsto
starts totocount
countdown
count downwith
down withsemaphoren
with semaphorenwith
semaphoren with1:
with 1:1:

sema.acquire();
sema.acquire();

If
IfIfthe
the semaphore is 0, the current thread blocked and must wait until another thread counts
thesemaphore
semaphoreisis0,0,thethecurrent
currentthread
threadblocked
blockedand andmust
mustwait
waituntil
untilanother
anotherthread
threadcounts
counts
the
the semaphoren
semaphoren up.
up. Otherwise
Otherwise the
the semaphore
semaphore is
is counted
counted down
down by
by 1
1 and
and the
the method
method
the semaphoren up. Otherwise the semaphore is counted down by 1 and the method
continues. In
continues. In this case,
case, it means that that the method
method getResource() call call a synchronized methodmethod
continues. Inthis this case,ititmeans
means thatthe the methodgetResource()
getResource() callaasynchronized
synchronized method
get(),
get(), there must find and returns aa Resource object. The method get() must at the same
get(), there
there must
must find
find and
and returns
returns a Resource
Resource object.
object. The
The method
method get()
get() must
must atat the
the same
same
time
time set the actual object as used. The method putResource() has as a parameter a Resource
timeset setthe
theactual
actualobject
objectasasused.
used.TheThemethod
methodputResource()
putResource()hashasasasaaparameter
parameteraaResource
Resource
object,
object, and
and the
the method
method has
has to
to release
release this
this object.
object. To
To this
this the
the method
method calls
calls aa synchronized
synchronized
object, and the method has to release this object. To this the method calls a synchronized
method unused(),
method unused(), and if if the object
object is used, it it is marked as as unused, and
and the method
method returns
method unused(),and and ifthethe objectisisused,
used, itisismarked
marked asunused,
unused, andthe the methodreturns
returns
true.
true. If so, then the method putResource() performs
true.IfIfso,
so,then
thenthe
themethod
methodputResource()
putResource()performs
performs

sema.release();
sema.release();

which
which means that the semaphore is counted up by 1, and at the same time it indicates that
whichmeans
meansthat
thatthe
thesemaphore
semaphoreisiscounted
countedupupby
by1,1,and
andatatthe
thesame
sametime
timeititindicates
indicatesthat
that
aaablocked
blocked thread
thread can
can now
now use
use the
the Resources
Resources object.
object.
blocked thread can now use the Resources object.

The
The class Worker is a class which defines aa thread that performs work by asking for a Resource
Theclass
classWorker
Workerisisaaclass
classwhich
whichdefines
defines athread
threadthat
thatperforms
performswork
workby byasking
askingfor
foraaResource
Resource
object.
object. There is not much to explain, but you must note that it is essential that the run()
object. There is not much to explain, but you must note that it is essential that the run()
There is not much to explain, but you must note that it is essential that the run()
method executes
method executes putResouce()
putResouce() since
since the
the semaphore
semaphore otherwise
otherwise not
not is
is counted
counted up.
up.
method executes putResouce() since the semaphore otherwise not is counted up.

Back
Back is the main() method, which starts aa number of worker threads. Here you must
Back isis the
the main()
main() method,
method, which
which starts
starts a number
number ofof worker
worker threads.
threads. Here
Here you
you must
must
notice
notice that
that it
it starts
starts more
more threads
threads than
than can
can simultaneously
simultaneously use
use the
the Resources
Resources object
object (twice
(twice
notice that it starts more threads than can simultaneously use the Resources object (twice
as many).
as many). It is to illustrate that that some of of the threads
threads is blocked byby the semaphore,
semaphore, and inin
as many). ItIt isis toto illustrate
illustrate that some
some of the
the threads isis blocked
blocked by the
the semaphore, and
and in
turn
turn becomes unblocked again.
turnbecomes
becomesunblocked
unblockedagain. again.

EXERCISE
EXERCISE8
EXERCISE 88
Create
Create a project that you can call SemaphoreProgram. The program is an example of using
Createaaproject
projectthat
thatyou
youcan
cancall
callSemaphoreProgram.
SemaphoreProgram.The
Theprogram
programisisan
anexample
exampleofofusing
using
both
both aa binary
binary semaphore
semaphore and
and aa counting
counting semaphore.
semaphore.
both a binary semaphore and a counting semaphore.

70
70
70
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools

Start by typing the following class, which is an encapsulating of a Map<Integer, String>,


Start by typing the following class, which is an encapsulating of a Map<Integer, String>,
when it is
Start a requirement that class,
the class must be written as a singleton:
when by
it istyping the following
a requirement that the which
class mustis be
anwritten
encapsulating of a Map<Integer, String>,
as a singleton:
when it is a requirement that the class must be written as a singleton:
class Storage
class
{ Storage
{private static int ID = 0; // the consecutive numbering of objects
private
private static int IDString>
Map<Integer, = 0; //cache
the consecutive numbering of objects
= new HashMap();
private Map<Integer, String> cache = new HashMap();
public int insert(String name)
public
{ int insert(String name)
{
// add a new name to the data structure identified by the next id
} // add a new name to the data structure identified by the next id
}
public String getName(int id)
public String
{ getName(int id)
{ // returns a name with an id or null, the id is not found
} // returns a name with an id or null, the id is not found
}
public int length()
{public int length()
{ // Returns the number of names
} // Returns the number of names
}}
}

The
The class
class should
should illustrate
illustrate aa data
data structure
structure consisting
consisting of
of names,
names, identified
identified by
by aa sequential
sequential
The class
number. should illustrate a data structure consisting of names, identified by a sequential
number.
number.
The
The goal
goal of
of the
the exercise
exercise isis to
to create
create threads
threads that
that reads
reads names
names (performing
(performing getName())
getName()) as as well
well
The
as goal of the exercise is to create threads that reads names (performing getName()) as well
as threads
threads that
that adds
adds names
names (performing
(performing insert()).
insert()). ItIt should
should be
be such
such that
that up
up toto 55 threads
threads
as threads
simultaneouslythat adds names (performing insert()). It should be such that up to 5 threads
simultaneously read, read, while
while only only aa single
single thread
thread can
can addadd names.
names. ItIt must
must bebe controlled
controlled by by
simultaneously
two read, while only a single thread can add names. It must be controlled by
two semaphores.
semaphores. To To make
make thingsthings aa little
little easier,
easier, you
you should
should encapsulate
encapsulate thethe two
two semaphores
semaphores
two
in semaphores.
the below classTo make
when it things
is a a little
requirement easier, you
that the should
class encapsulate
must be the
written two
as a semaphores
singleton:
in the below class when it is a requirement that the class must be written as a singleton:
in the below class when it is a requirement that the class must be written as a singleton:
class StorageLock
class
{ StorageLock
{private final Semaphore writeLock = new Semaphore(1);

private final Semaphore writeLock = new Semaphore(1);
private final Semaphore readLock = new Semaphore(5);
private final Semaphore readLock = new Semaphore(5);
public void getWriteLock() throws InterruptedException
public
{ void getWriteLock() throws InterruptedException
{ writeLock.acquire();
} writeLock.acquire();
}

71
71
JAVA 8:MULTITHREADEDPROGRAMS
JAVA PROGRAMS Concurrency Tools
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS ConCurrenCy
ConCurrenCy tools
tools

public
public void
void releaseWriteLock()
releaseWriteLock()
{{
writeLock.release();
writeLock.release();
}}

public
public void
void getReadLock()
getReadLock() throws
throws InterruptedException
InterruptedException
{{
readLock.acquire();
readLock.acquire();
}}

public
public void
void releaseReadLock()
releaseReadLock()
{{
readLock.release();
readLock.release();
}}
}}

As
Asaaanext
As nextstep
next stepyou
step youmust
you mustwrite
must writeaaaWriter
write Writerclass
Writer classthat
class thatdefines
that definesaaaRunnable
defines Runnabletype
Runnable typethat
type thatcan
that canadd
can add
add
names
namesto
names totothe
thedata
the datastructure
data structureStorage:
structure Storage:
Storage:

class
class Writer
Writer implements
implements Runnable
Runnable
{{
private
private String[]
String[] names;
names;

Free eBook on
Learning & Development
By the Chief Learning Officer of McKinsey

Download Now

72
72
72
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Concurrencytools
ConCurrenCy Tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools

public
public Writer(String[]
Writer(String[] names)
names)
{
{
this.names
this.names =
= names;
names;
}
}

public
public void
void run()
run()
{
{
for
for (String
(String name
name :
: names)
names)
{
{
//
// set
set a
a write
write lock
lock
// add name
// add name
//
// release
release the
the lock
lock
//
// sleep a random
sleep a random time
time less
less than
than 2
2 seconds
seconds
}
}
}
}
}
}

You
You must corresponding write aa class Reader that defines aa Runnable type that can read the
You must
must corresponding
corresponding write
write a class
class Reader
Reader that
that defines
defines a Runnable
Runnable type
type that
that can
can read
read the
the
names
names in the data structure Storage:
names in
in the
the data
data structure
structure Storage:
Storage:
class Reader implements
class Reader implements Runnable
Runnable
{
{
public
public void
void run()
run()
{
{
while
while (true)
(true)
{
{
//
// set
set aa read
read lock
lock
//
// read a name with
read a name with aa random
random id
id
// release the
// release the locklock
//
// prints
prints thethe name,
name, if
if it
it is
is not
not null
null
//
// sleep a random time less than
sleep a random time less than a
a ½
½ second
second
}
}
}
}
}
}

Then there isis the


Then the only main
main program:
Then there
there is the only
only main program:
program:

public
public class
class SemaphoreProgram
SemaphoreProgram
{
{

private static final String[] boys = ... // array with 10 boy names
private static final String[] boys = ... // array with 10 boy names
private static final String[] girls = ... // array with 10 girl names
private static final String[] girls = ... // array with 10 girl names

73
73
73
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools

public static void main(String[] args)


{
public static void main(String[] args)
{ // creates a thread to a Writer object which adds boy names
// creates a thread to a Writer object which adds boygirl names
names
// Creates
creates 10 Reader to
a thread threads, when
a Writer it should
object which be daemon
adds girl threads
names
// start all
Creates 10 the threads
Reader threads, when it should be daemon threads
// the primary
start all thethread
threadsshould join the two writer threds
} // the primary thread should join the two writer threds
}}
}
Test
Test the
the program
program and
and check
check that
that everything
everything works
works as
as intended.
intended.
Test the program and check that everything works as intended.
8.6 PHASER
8.6 PHASER
8.6 PHASER
AAPhaser
Phaserlooks
lookslike
likeaaCyclicBarrier,
CyclicBarrier,butbutisismore
moreflexible.
flexible.In Inthe
thesame
sameway wayasaswith
withaaCyclicBarrier
CyclicBarrier
A
you Phaser
you can looks
can be like
be achieve a
achieve thatCyclicBarrier,
that aa number
number of but is more
of threads flexible.
threads are
are waitingIn the
waiting at same
at the way
the barrier,as with
barrier, until a CyclicBarrier
until the
the last
last thread
thread
you can be
isis arriving, achieve
arriving, but
but in that a
in contrast number
contrast to of threads
to aa CyclicBarrier, are
CyclicBarrier, that waiting
that waits at
waits for the barrier,
for aa fixed until
fixed number
number ofthe last thread
of threads,
threads, aa
isPhaser
arriving,
Phaser act butaa barrier
act as
as in contrast
barrier for ato
for a CyclicBarrier,
a variable
variable number that
number threads, waits
threads, andforthere
and a fixed
there may
maynumber
be of threads,
be several
several phases –a–
phases
Phaser
barriers.
barriers. act
Theas following
The a barrier program
following for a variable
program startsnumber
starts 55 threads
threadsthreads,
in and to
in addition
addition therethemay
to the be several
primary
primary thread,phases
thread, and –
and the
the
barriers.
executionThe
execution of following
of the program
the 66 threads
threads are starts 5 threads
are synchronized
synchronized by ain
by addition
a Phaser
Phaser to the
object
object withprimary
with thread, and the
44 phases:
phases:
execution of the 6 threads are synchronized by a Phaser object with 4 phases:
package thread20;
package thread20;
import java.util.*;
import java.util.concurrent.*;
java.util.*;
import java.util.concurrent.*;
public class Thread20
{
public class Thread20
{public static void main(String[] args)
{
public static void main(String[] args)
{ Phaser phaser = new Phaser(1);
Thread thread1 == new
Phaser phaser new Phaser(1);
Thread(new Worker(phaser), "Thread-1");
Thread thread2
thread1 = new Thread(new Worker(phaser), "Thread-2");
"Thread-1");
Thread thread3
thread2 = new Thread(new Worker(phaser), "Thread-3");
"Thread-2");
Thread thread4
thread3 = new Thread(new Worker(phaser), "Thread-4");
"Thread-3");
Thread thread5
thread4 = new Thread(new Worker(phaser), "Thread-5");
"Thread-4");
System.out.println("\n-------- Start Phaser ---------------");
Thread thread5 = new Thread(new Worker(phaser), "Thread-5");
thread1.start();
System.out.println("\n-------- Start Phaser ---------------");
thread2.start();
thread1.start();
thread3.start();
thread2.start();
thread4.start();
thread3.start();
thread5.start();
thread4.start();
work(phaser);
thread5.start();
work(phaser);
work(phaser);
work(phaser);
work(phaser);

74
74
74
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Concurrencytools
ConCurrenCy Tools

phaser.arriveAndDeregister();
if(phaser.isTerminated()) System.out.println("\nThe Phaser object terminated");
}

private static void work(Phaser phaser)


{
int phase = phaser.getPhase();
phaser.arriveAndAwaitAdvance();
System.out.println("------ Phase – " + phase + " is terminated ----------");
}
}

class Worker implements Runnable


{
private static final Random rand = new Random();
private Phaser phaser;
private double value = 0;

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

75
75
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools

public Worker(Phaser phaser)


{
this.phaser = phaser;
this.phaser.register();
System.out.println("New thred registered: " +
Thread.currentThread().getName());
}

public void run()


{
todo(2);
todo(3);
todo(5);
result();
phaser.arriveAndDeregister();
}

private void todo(int t)


{
System.out.println(Thread.currentThread().getName() +
" – has reached the barrier and works in phase " +
phaser.getPhase() + ", Value = " + value);
phaser.arriveAndAwaitAdvance();
work(rand.nextInt(Integer.MAX_VALUE), t);
}

private void result()


{
System.out.println(Thread.currentThread().getName() +
" – has reached the barrier and works in phase " +
phaser.getPhase() + ", Value = " + value);
phaser.arriveAndAwaitAdvance();
}

private void delay(int time)


{
try
{
Thread.sleep(time);
}
catch (InterruptedException e)
{
}
}

76
76
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA
JAVA8:MULTITHREADED
JAVA
JAVA
JAVA 8:MULTITHREADEDPROGRAMS
8:MULTITHREADED
8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS
PROGRAMS
PROGRAMS ConCurrenCy
ConCurrenCytools
ConCurrenCy
ConCurrenCy
ConCurrenCy tools
tools
tools
tools

private
private void
private
private void work(long
void
void work(long n,
work(long
work(long n, int
n,
n, int t)
int
int t)
t)
t)
{{{{
for
for (int
for
for (int iiii ==== 0;
(int
(int 0; iiii <<<< n;
0;
0; n; ++i)
n;
n; ++i) value
++i)
++i) value ==== Math.sqrt(t);
value
value Math.sqrt(t);
Math.sqrt(t);
Math.sqrt(t);
}}}}
}}}}

The
Theclass
The
The classWorker
class
class Workerdefines
Worker
Worker definesthe
defines
defines thesecondary
the
the secondarythreads.
secondary
secondary threads.The
threads.
threads. Theconstructor
The
The constructorhas
constructor
constructor hasaaaaPhaser
has
has Phaserobject
Phaser
Phaser objectas
object
object asaaaa
as
as
parameter,
parameter,and
parameter,
parameter, andthe
and
and theconstructor
the
the constructorsign
constructor
constructor signup
sign
sign upto
up
up totothe
to thePhaser
the
the Phaserobject
Phaser
Phaser objectas
object
object asone
as
as oneof
one
one ofthe
of
of thethreads
the
the threadswhich
threads
threads which
which
which
the
the
the object
object
the object has
has
object has to
to
has to wait
wait
to wait for:
for:
wait for:
for:

this.phaser.register();
this.phaser.register();
this.phaser.register();
this.phaser.register();

The
The run()
The
The run() method
run()
run() method executes
method
method executes four
executes
executes four methods
four
four methods (calls
methods
methods (calls the
(calls
(calls the method
the
the method todo()
method
method todo() three
todo()
todo() three times
three
three times and
times
times and the
and
and the
the
the
method
method
method result()
result()
result() once).
once).
once). Each
Each
Each of
of
of these
these
these methods
methods
methods carry
carry
carry out
out
out some
some
some
method result() once). Each of these methods carry out some work in a phase. That is that work
work
work in
in
in a
aa phase.
phase.
phase. That
That
That is
is
is that
that
that
the
thefirst
the
the firsttodo()
first
first todo()is
todo()
todo() isfirst
isis firstperformed
first
first performedwhen
performed
performed whenall
when
when allthreads
all
all threadshave
threads
threads havereached
have
have reachedthe
reached
reached thefirst
the
the firstbarrier,
first
first barrier,the
barrier,
barrier, thenext
the
the next
next
next
todo()
todo()
todo() when
when
when all
all
all threads
threads
threads have
have
have reached
reached
reached the
the
the next
next
next barrier
barrier
barrier and
and
and soso
so on.
on.
on.
todo() when all threads have reached the next barrier and so on. If you look at each phase’s If
If
If you
you
you look
look
look at
at
at each
each
each phase’s
phase’s
phase’s
methods,
methods,it
methods,
methods, itititisisnot
isis notso
not
not soimportant,
so
so important,what
important,
important, whatthey
what
what theydo,
they
they do,but
do,
do, butthey
but
but theyperform
they
they performthe
perform
perform themethod
the
the method
method
method

phaser.arriveAndAwaitAdvance();
phaser.arriveAndAwaitAdvance();
phaser.arriveAndAwaitAdvance();
phaser.arriveAndAwaitAdvance();

whichmeans
which
which
which meansthat
means
means thatthe
that
that thethread
the
the threadmust
thread
thread mustwait
must
must waitat
wait
wait atthe
at
at thebarrier
the
the barrieruntil
barrier
barrier untilall
until
until allthreads
all
all threadshave
threads
threads havereached.
have
have reached.The
reached.
reached. The
The
The
Phaserobject
Phaser
Phaser
Phaser objectis
object
object iscreated
isis createdin
created
created inthe
in
in themain()
the
the main()method:
main()
main() method:
method:
method:

Phaser
Phaser phaser
Phaser
Phaser phaser ==== new
phaser
phaser new Phaser(1);
new
new Phaser(1);
Phaser(1);
Phaser(1);

wherethere
where
where
where thereis
there
there isregistered
isis registeredaaaasingle
registered
registered singlethread,
single
single thread,which
thread,
thread, whichis
which
which isthe
isis theprimary
the
the primarythread.
primary
primary thread.The
thread.
thread. Theprimary
The
The primarythread
primary
primary thread
thread
thread
creates then
creates
creates
creates then 5555 other
then
then other threads
other
other threads and
threads
threads and start
and
and start them
start
start them and
them
them and then
and
and then perform
then
then perform the
perform
perform the method
the
the method work().
method
method work(). The
work().
work(). The
The
The
importantthing
important
important
important thinghere
thing
thing hereis
here
here isthe
isis thestatement
the
the statement
statement
statement

phaser.arriveAndAwaitAdvance();
phaser.arriveAndAwaitAdvance();
phaser.arriveAndAwaitAdvance();
phaser.arriveAndAwaitAdvance();

which
whichmeans
which
which meansthat
means
means thatall
that
that allthreads
all
all threadsincl.
threads
threads incl.the
incl.
incl. theprimary
the
the primarythread
primary
primary threadwill
thread
thread willhave
will
will haveto
have
have towait
to
to waitat
wait
wait ataaaabarrier
at
at barrieruntil
barrier
barrier untilall
until
until all
all
all
the
the
the other
other
the other threads
threads
other threads arrives.
arrives.
threads arrives. If
arrives. IfIf the
the
If the program
program is
program isis
the program performed
performed
is performed the
the
performed the result
result
the result is:
is:
result is:
is:

New
New
New
New thred
thred
thred
thred registered:
registered:
registered:
registered: main
main
main
main
New
New
New
New thred
thred
thred
thred registered:
registered:
registered:
registered: main
main
main
main
New
New
New
New thred
thred
thred
thred registered:
registered:
registered:
registered: main
main
main
main
New
New
New
New thred
thred
thred
thred registered:
registered:
registered:
registered: main
main
main
main
New
New
New
New thred
thred
thred
thred registered:
registered:
registered:
registered: main
main
main
main

77
77
77
77
77
77
77
JAVA 8:MULTITHREADED PROGRAMS
JAVA 8:MULTITHREADED PROGRAMS
Concurrency Tools
ConCurrenCy tools

-------- Start Phaser ---------------


Thread-2 – has reached the barrier and works in phase 0, Value = 0.0
Thread-1 – has reached the barrier and works in phase 0, Value = 0.0
Thread-4 – has reached the barrier and works in phase 0, Value = 0.0
Thread-3 – has reached the barrier and works in phase 0, Value = 0.0
Thread-5 – has reached the barrier and works in phase 0, Value = 0.0
------ Phase – 0 is terminated ----------
Thread-2 – has reached the barrier and works in phase 1, Value = 1.4142135623730951
Thread-5 – has reached the barrier and works in phase 1, Value = 1.4142135623730951
Thread-4 – has reached the barrier and works in phase 1, Value = 1.4142135623730951
Thread-3 – has reached the barrier and works in phase 1, Value = 1.4142135623730951
Thread-1 – has reached the barrier and works in phase 1, Value = 1.4142135623730951
------ Phase – 1 is terminated ----------
Thread-4 – has reached the barrier and works in phase 2, Value = 1.7320508075688772
Thread-1 – has reached the barrier and works in phase 2, Value = 1.7320508075688772
Thread-5 – has reached the barrier and works in phase 2, Value = 1.7320508075688772
Thread-3 – has reached the barrier and works in phase 2, Value = 1.7320508075688772

360°
Thread-2 – has reached the barrier and works in phase 2, Value = 1.7320508075688772
------ Phase – 2 is terminated ----------

.
Thread-2 – has reached the barrier and works in phase 3, Value = 2.23606797749979

thinking
Thread-1 – has reached the barrier and works in phase 3, Value = 2.23606797749979
Thread-3 – has reached the barrier and works in phase 3, Value = 2.23606797749979
Thread-5 – has reached the barrier and works in phase 3, Value = 2.23606797749979
Thread-4 – has reached the barrier and works in phase 3, Value = 2.23606797749979

360°
thinking . 360°
thinking .
Discover the truth at www.deloitte.ca/careers Dis

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers © Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities. 78

Discover the truth at www.deloitte.ca/careers


78
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS ConCurrenCy
Concurrency tools
Tools

8.7 LOCKS
8.7 LOCKS
As
As seen
seen in
in the
the previous
previous chapter,
chapter, Java
Java allows
allows toto synchronize
synchronize threads
threads so so that
that threads
threads cancan safely
safely
updating shared objects, and so that a thread’s updating of an object is
updating shared objects, and so that a thread’s updating of an object is visible to all other visible to all other
threads.
threads. This
This isis done
done byby placing
placing codecode inin aa critical
critical region
region where
where youyou can can ensure
ensure mutual
mutual
exclusion
exclusion by by using
using locks.
locks. Each
Each object
object isis associated
associated with
with aa lock
lock inin the
the form
form of of aa monitor,
monitor,
which
which ensures
ensures that
that only
only one
one thread
thread atat aa time,
time, can
can performs
performs thethe statements
statements in in aa critical
critical
region.
region. A thread can only enter a critical region and obtain the lock if the lock is not used
A thread can only enter a critical region and obtain the lock if the lock is not used
by
by another thread, and if it is the current thread is blocked until another thread exits the
another thread, and if it is the current thread is blocked until another thread exits the
critical
critical region
region and
and releases
releases the
the lock.
lock. This
This mechanism
mechanism will will also
also ensure
ensure that
that when
when aa thread
thread
locks
locks aa critical
critical region,
region, that
that values
values ofof shared
shared variables
variables stored
stored inin memory
memory also also ifif necessary
necessary
updates
updates copies in a cache. The opposite happens when a thread exits the critical region and
copies in a cache. The opposite happens when a thread exits the critical region and
releases the lock, the cached values are written back
releases the lock, the cached values are written back to memory. to memory.

To
To facilitate
facilitate the
the work
work synchronization
synchronization tools
tools defines
defines more
more interfaces
interfaces and
and classes
classes that
that will
will
make it easier to work with locks, and as an example uses the following program
make it easier to work with locks, and as an example uses the following program a lock: a lock:

package thread21;

import java.util.concurrent.*;
import java.util.concurrent.locks.*;

public class Thread21


{
public static void main(String[] args)
{
ExecutorService executor = Executors.newFixedThreadPool(3);
final ReentrantLock lock = new ReentrantLock();
executor.execute(new Worker("A", lock));
executor.execute(new Worker("B", lock));
executor.execute(new Worker("C", lock));
try
{
executor.awaitTermination(10, TimeUnit.SECONDS);
}
catch (Exception ex)
{
}
executor.shutdownNow();
}
}

79
79
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Concurrencytools
ConCurrenCy Tools

class Worker implements Runnable


{
private final Lock lock;
private final String name;

Worker(String name, Lock lock)


{
this.name = name;
this.lock = lock;
}

public void run()


{
System.out.println(name + " startet");
lock.lock();
try
{
System.out.printf("%s Critical region.\n",name);
System.out.printf("%s: Works.\n", name);
Thread.sleep(2000);
System.out.printf("%s Terminates.\n", name);
}
catch (Exception ex)
{
}
finally
{
lock.unlock();
}
}
}

AA lock
lock isis represented
represented byby the
the class
class ReentrantLock
ReentrantLock that
that implements
implements the
the interface
interface Lock,
Lock, and
and
the
the program
program creates
creates such
such aa lock:
lock:

ReentrantLock lock = new ReentrantLock();

Next
Next thethe program
program startstart three
three threads,
threads, andand each
each thread
thread carry
carry out
out work
work in in aa critical
critical region
region
that
that isis defined
defined with
with the the lock.
lock. There
There isis not
not much
much to to explain,
explain, and
and itit isis in
in principle
principle simple
simple
to
to work
work withwith aa lock,
lock, butbut itit isis important
important to to ensure
ensure that
that the
the lock
lock isis always
always released
released again,
again,
and
and aa good
good place
place isis to
to lock
lock up
up isis in
in aa finally
finally block.
block. IfIf the
the above
above program
program isis performed,
performed, the the
result could be the following:
result could be the following:

80
80
JAVA 8:MULTITHREADED
JAVA 8:MULTITHREADED PROGRAMS
PROGRAMS Concurrency
ConCurrenCy Tools
tools

A startet
C startet
B startet
A Critical region.
A: Works.
A Terminates.
C Critical region.
C: Works.
C Terminates.
B Critical region.
B: Works.
B Terminates.

Basic
Basic is
is synchronization
synchronization based
based onon critical
critical regions
regions on
on the
the use
use of
of synchronized
synchronized and
and wait()
wait() and
and
notify(),
notify(), and you can say that a Lock replaces the use of synchronized. Similarly, an object of
and you can say that a Lock replaces the use of synchronized. Similarly, an object of
the type Condition is an object that replaces the use of wait() and notify(). Below
the type Condition is an object that replaces the use of wait() and notify(). Below is shown is shown
aa program
program that
that solves
solves the
the producer-consumer
producer-consumer problemproblem inin which
which there
there are
are two
two threads,
threads,
respectively
respectively updating and reading a shared resource, but this time the problem is solved by
updating and reading a shared resource, but this time the problem is solved by
aa ReentrantLock and a Condition
ReentrantLock and a Condition object: object:

We will turn your CV into


an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

81
81
JAVA 8:MULTITHREADED
JAVA 8:MULTITHREADED PROGRAMS
PROGRAMS Concurrency tools
ConCurrenCy Tools

package thread22;

import java.util.concurrent.locks.*;

public class Thread22


{
public static void main(String[] args)
{
Shared shared = new Shared();
new Producer(shared).start();
new Consumer(shared).start();
}
}

class Shared
{
private char value; // the shared resource
private volatile boolean ok = false;
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();

public Lock getLock()


{
return lock;
}

public char getValue() throws InterruptedException


{
lock.lock();
try
{
while (!ok) condition.await();
ok = false;
return value;
}
finally
{
condition.signal();
lock.unlock();
}
}

public void setValue(char value) throws InterruptedException


{
lock.lock();
try
{

82
82
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Concurrencytools
ConCurrenCy Tools

while (ok) condition.await();


this.value = value;
ok = true;
}
finally
{
condition.signal();
lock.unlock();
}
}
}

class Producer extends Thread


{
private final Shared shared;

Producer(Shared shared)
{
this.shared = shared;
}

public void run()


{
for (char ch = 'A'; ch <= 'Z'; ++ch)
{
try
{
shared.setValue(ch);
}
catch (InterruptedException ex)
{
}
}
}
}

class Consumer extends Thread


{
private final Lock lock;
private final Shared shared;

Consumer(Shared shared)
{
this.shared = shared;
lock = shared.getLock();
}

83
83
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Concurrencytools
ConCurrenCy Tools

public void run()


{
char ch = ' ';
do
{
try
{
lock.lock();
System.out.print(ch = shared.getValue());
}
catch (InterruptedException ex)
{
}
finally
{
lock.unlock();
}
}
while (ch != 'Z');
System.out.println();
}
}

84
84
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools

The program is similar to the previous solution, but you should notice how the class Shared
The program is similar to the previous solution, but you should notice how the class Shared
creates a Condition object using the Lock object. This object is used in both getValue() and
creates a Condition object using the Lock object. This object is used in both getValue() and
setValue() to perform await(), and within the critical region the method performs a signal()
setValue() to perform await(), and within the critical region the method performs a signal()
corresponding to the notify().
corresponding to the notify().

EXERCISE 9
EXERCISE 9
In this exercise you have to solve the same task as in exercise 5, but this time instead of
In this exercise you have to solve the same task as in exercise 5, but this time instead of
using synchronized, wait() and notify() you must use the types Lock and Condition.
using synchronized, wait() and notify() you must use the types Lock and Condition.

8.8 READWRITELOCK
8.8 READWRITELOCK
Many times, a data structure is read more often than it needs to be adjusted, and you
Many times, a data structure is read more often than it needs to be adjusted, and you
can have multiple threads that simultaneously read the data structure, while only one or
can have multiple threads that simultaneously read the data structure, while only one or
a few threads need to update it. Accordingly, there is a lock, called a ReadWriteLock that
a few threads need to update it. Accordingly, there is a lock, called a ReadWriteLock that
ensures that multiple threads can simultaneously read a data structure, while only a single
ensures that multiple threads can simultaneously read a data structure, while only a single
can update. The following program creates a thread and initializes a Map<String, String>
can update. The following program creates a thread and initializes a Map<String, String>
with the Danish zip codes where the code is the key. In addition, the program creates three
with the Danish zip codes where the code is the key. In addition, the program creates three
methods that read the data structure and print an item on the screen. To synchronize the
methods that read the data structure and print an item on the screen. To synchronize the
threads access to the data structure is used a ReadWriteLock:
threads access to the data structure is used a ReadWriteLock:
package thread23;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;

public class Thread23


{
private static final ReadWriteLock lock = new ReentrantReadWriteLock(true);
private static final Map<String, String> dictionary = new HashMap();
private static final List<String> keys = new ArrayList();
private static final Random rand = new Random();

public static void main(String[] args)


{
new Thread23().doWork();
}

private void doWork()


{
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.submit(new Writer());
executor.submit(new Reader());

85
85
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS Concurrency
ConCurrenCy Tools
tools

executor.submit(new Reader());
executor.submit(new Reader());
}

class Reader implements Runnable


{
public void run()
{
while (true)
{
lock.readLock().lock();
try
{
System.out.println("[" + Thread.currentThread().getId() + "] " +
dictionary.get(keys.get(rand.nextInt(keys.size()))));
}
finally
{
lock.readLock().unlock();
}
try
{
Thread.sleep(100);
}
catch (InterruptedException ie)
{
}
}
}
}

class Writer implements Runnable


{
public void run()
{
for (int i = 0; i < data.length; ++i)
{
lock.writeLock().lock();
try
{
String[] elems = data[i].split(";");
dictionary.put(elems[0], elems[0] + " " + elems[1]);
keys.add(elems[0]);
}
finally
{
lock.writeLock().unlock();
}

86 86
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS Concurrency
ConCurrenCy Tools
tools

try
{
Thread.sleep(200);
}
catch (InterruptedException ie)
{
}
}
System.out.println("Dictionary initialiseret.............................");
}
}

private static String[] data =


{
"0800;Høje Taastrup",
"0900;København C",
"0999;København C",
"1000;København K",
"1050;København K",
...
"9990;Skagen"
};
}

AXA Global
Graduate Program
Find out more and apply

87
87
JAVA 8:MULTITHREADED
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools
tools
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS ConCurrenCy
Concurrency Tools

The
The zip codes are laid out in an array at the end of the program. At the start of the main
The zip
zip codes
codes are
are laid
laid out
out in
in an
an array
array atat the
the end
end ofof the
the program.
program. At
At the
the start
start ofof the
the main
main
class
class is
is defined
defined a
a ReadWriteLock:
ReadWriteLock:
class is defined a ReadWriteLock:

ReadWriteLock
ReadWriteLock lock
lock =
= new
new ReentrantReadWriteLock(true);
ReentrantReadWriteLock(true);

and also
and also a HashMap called called dictionary, and
and an ArrayList,
ArrayList, that should
should be used
used for keys.
keys. The
and also aa HashMap
HashMap called dictionary,
dictionary, and an an ArrayList, that
that should bebe used forfor keys. The
The
class
class Writer defines the thread to initialize the dictionary and you should notice, that it
class Writer
Writer defines
defines the
the thread
thread to
to initialize
initialize the
the dictionary
dictionary andand you
you should
should notice,
notice, that
that itit
defines
defines a critical region using the write lock. This ensures that only one thread can use the
definesaacritical
criticalregion
regionusing
usingthe
thewrite
writelock.
lock.This
Thisensures
ensuresthat
thatonly
onlyone
onethread
threadcancanuse
usethe
the
code
code that
that updates
updates the
the data
data structure.
structure. The
The class
class Reader
Reader similarly
similarly defines
defines aa thread
thread to
to read
read
code that updates the data structure. The class Reader similarly defines a thread to read
the data
the data structure, which
which reads aa data
data item with
with a random key. key. Here you
you should note
note that
the datastructure,
structure, whichreadsreads a dataitem
item withaarandom
random key.Here Here youshould
should notethatthat
the
the critical region is defined by means of the read lock and thus more readers can use the
the critical
critical region
region isis defined
defined by
by means
means ofof the
the read
read lock
lock and
and thus
thus more
more readers
readers can
can use
use the
the
critical
critical region.
critical region.
region.

EXERCISE 10
EXERCISE 10
EXERCISE 10
In
In this exercise you have to solve the same problem as in exercise 8, but locking must be
In this
this exercise
exercise you
you have
have to
to solve
solve the
the same
same problem
problem asas in
in exercise
exercise 8,8, but
but locking
locking must
must be
be
done with
done with aa ReadWriteLock
ReadWriteLock instead
instead ofof the
the class
class StorageLock.
StorageLock. Start
Start by
by creating
creating aa copy
copy of
of
done with a ReadWriteLock instead of the class StorageLock. Start by creating a copy of
the
the program SemaphoreProgram and call the new project for ReadWriteProgram. Create a
the program
program SemaphoreProgram
SemaphoreProgram and and call
call the
the new
new project
project forfor ReadWriteProgram.
ReadWriteProgram. Create
Create aa
ReadWriteLock:
ReadWriteLock:
ReadWriteLock:

ReadWriteLock
ReadWriteLock lock
lock =
= new
new ReentrantReadWriteLock(true);
ReentrantReadWriteLock(true);

and
and delete the class StorageLock. Adjust then the code to instead use the new lock.
and delete
delete the
the class
class StorageLock.
StorageLock. Adjust
Adjust then
then the
the code
code to
to instead
instead use
use the
the new
new lock.
lock.

8.9
8.9 COLLECTIONS
COLLECTIONS
8.9 COLLECTIONS
Java was
Java was from the
the start equipped
equipped with collection
collection classes for for the most
most commonly used used data
Java was from
from the start
start equipped with with collection classesclasses for thethe most commonly
commonly used data data
structures,
structures, and they were all thread safe, so they could be used safely in multithreaded
structures, and
and they
they were
were all
all thread
thread safe,
safe, so
so they
they could
could be be used
used safely
safely in
in multithreaded
multithreaded
applications.
applications. At the time, it was really thought, for the goal of Java was to develop an
applications. AtAt the
the time,
time, itit was
was really
really thought,
thought, for for the
the goal
goal ofof Java
Java was
was to
to develop
develop an an
object-oriented
object-oriented programming
programming language
language that
that was
was easy
easy to
to use,
use, and
and which
which resulted
resulted in
in robust
robust
object-oriented programming language that was easy to use, and which resulted in robust
programs. However,
programs. However, the language
language quickly became became so popular
popular that it it was used
used also for
for the
programs. However, the the language quickly
quickly became so so popular that that it was
was used also
also for the
the
development
development of large-scale distributed solutions, and then performance was an issue, and
development ofof large-scale
large-scale distributed
distributed solutions,
solutions, and and then
then performance
performance was was an
an issue,
issue, and
and
it was
itit was a problem that the Java’s collection classes were thread safe, especially because in
was aa problem
problem thatthat the
the Java’s
Java’s collection
collection classes
classes were
were thread
thread safe,
safe, especially
especially because
because in in
most
most cases
cases you
you do
do not
not have
have the
the need.
need. The
The result
result was,
was, that
that some
some new
new collection
collection classes
classes was
was
most cases you do not have the need. The result was, that some new collection classes was
developed (those
developed (those that are
are discussed in in this books),
books), and they they are notnot thread safe.
safe. Occasionally
developed (thosethat that arediscussed
discussed inthis this books),and and theyare are notthread
thread safe.Occasionally
Occasionally
you
you has, however, the needs that collections are thread safe, and to solve these problems is
youhas,
has,however,
however,the theneeds
needsthatthatcollections
collectionsare arethread
threadsafe,safe,and
andto tosolve
solvethese
theseproblems
problemsisis
defined
defined some wrapper classes, which ensures that the classes can be used with multithreaded
definedsome
somewrapper
wrapperclasses,
classes,which
whichensures
ensuresthatthatthetheclasses
classescancanbe beused
usedwith
withmultithreaded
multithreaded
applications.
applications. These wrapper classes are simple to use and the following example shows aa
applications. These wrapper classes are simple to use and the following example shows
These wrapper classes are simple to use and the following example shows a
program, that
program, that use
use aa thread
thread safe
safe ArrayList:
ArrayList:
program, that use a thread safe ArrayList:

88
88
88
JAVA 8:MULTITHREADED PROGRAMS
JAVA PROGRAMS Concurrency Tools
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS ConCurrenCy
ConCurrenCy tools
tools

package thread24;
package thread24;

import java.util.*;
import java.util.*;
public
public class Thread24
class Thread24
{
{
public
public static
static void
void main(String[]
main(String[] args)
args)
{
{
List<Integer>
List<Integer> list
list == java.util.Collections.synchronizedList(new
java.util.Collections.synchronizedList(new ArrayList());
ArrayList());
for (int
for (int ii =
= 1;
1; ii <=
<= 100;
100; ++i)
++i) list.add(i);
list.add(i);
int
int sum
sum == 0;
0;
for (Integer
for (Integer tt :
: list)
list) sum
sum +=
+= t;
t;
System.out.println(sum);
System.out.println(sum);
}
}
}
}

and there
and
and there are
there are similar
are similar wrapper
similar wrapper classes
wrapper classes to
classes to the
to the other
the other collection
other collection classes.
collection classes. However,
classes. However, this
However, this solution
this solution
solution
also has
also
also has its
has its drawbacks,
its drawbacks, and
drawbacks, and in
and in particular
in particular it
particular it can
it can cause
can cause problems
cause problems if
problems if you
if you iterate
you iterate over
iterate over aaa collection
over collection
collection
while another
while
while another thread
another thread updates.
thread updates. This
updates. This will
This will result
will result in
result in an
in an exception,
an exception, and
exception, and it
and it is
it is therefore
is therefore necessary
therefore necessary
necessary
putting aaa lock
putting
putting lock by
lock by yourself.
by yourself. Therefore
yourself. Therefore –
Therefore –– and
and also
and also for
also for other
for other reasons
other reasons –
reasons –– there
there are
there are defined
are defined some
defined some
some
special thread
special
special thread safe
thread safe collection
safe collection classes:
collection classes:
classes:

1.
1. BlockingQueue is
1. BlockingQueue
BlockingQueue is aaa subinterface
is subinterface to
subinterface to java.util.Queue
to java.util.Queue that
java.util.Queue that implements
that implements blocking
implements blocking
blocking
operations that
operations
operations that wait
that wait for
wait for the
for the queue
the queue is
queue is not
is not empty
not empty before
empty before they
before they return
they return an
return an item
an item and
item and
and
do not
do
do not add
not add an
add an item
an item before
item before the
before the queue
the queue has
queue has room.
has room. The
room. The interface
The interface is
interface is implemented
is implemented
implemented
by the
by
by the following
the following classes:
following classes: ArrayBlockingQueue,
classes: ArrayBlockingQueue, LinkedBlockingQueue,
ArrayBlockingQueue, LinkedBlockingQueue, DelayQueue,
LinkedBlockingQueue, DelayQueue,
DelayQueue,
PriorityBlockingQueue and
PriorityBlockingQueue
PriorityBlockingQueue and SynchronousQueue
and SynchronousQueue and
SynchronousQueue and indirectly
and indirectly by
indirectly by LinkedBlockingDeque
by LinkedBlockingDeque
LinkedBlockingDeque
and LinkedTransferQueue.
and
and LinkedTransferQueue.
LinkedTransferQueue.
2. ConcurrentMap
2.
2. ConcurrentMap is
ConcurrentMap is aaa subinterface
is subinterface to
subinterface to java.util.Map
to java.util.Map defining
java.util.Map defining thread
defining thread safe
thread safe putIfAbsent(),
safe putIfAbsent(),
putIfAbsent(),
Remove() and
Remove()
Remove() and replace()
and replace() methods.
replace() methods. The
methods. The interface
The interface is
interface is implemented
is implemented by
implemented by ConcurrentHashMap,
by ConcurrentHashMap,
ConcurrentHashMap,
ConcurrentNavigableMap and
ConcurrentNavigableMap
ConcurrentNavigableMap and ConcurrentSkipListMap.
and ConcurrentSkipListMap.
ConcurrentSkipListMap.

As an
As
As an example
an example is
example is shown
is shown aaa program
shown program which
program which solves
which solves the
solves the producer-consumer
the producer-consumer problem
producer-consumer problem by
problem by means
by means
means
of aaa BlockingQueue:
of
of BlockingQueue:
BlockingQueue:

package thread25;
package thread25;

import
import java.util.concurrent.*;
java.util.concurrent.*;

public
public class
class Thread25
Thread25
{
{
public
public static
static void
void main(String[]
main(String[] args)
args)
{
{

89
89
89
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools

final BlockingQueue<Character> queue = new ArrayBlockingQueue(26);


final ExecutorService executor = Executors.newFixedThreadPool(2);
final CountDownLatch done = new CountDownLatch(2);
executor.execute(new Producer(queue, done));
executor.execute(new Consumer(queue, done));
try
{
done.await();
}
catch (InterruptedException ex)
{
}
executor.shutdownNow();
}
}

class Consumer implements Runnable


{
private BlockingQueue<Character> queue;
private CountDownLatch done;

I joined MITAS because �e Graduate Programme


for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work helping foremen advis
he
International
al opportunities
Internationa
work
�ree woor placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
work
�ree wo or placements ssolve pr

90
90
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools

public Consumer(BlockingQueue<Character> queue, CountDownLatch done)


{
this.queue = queue;
this.done = done;
}

public void run()


{
char ch = '\0';
do
{
try
{
System.out.print(ch = queue.take());
}
catch (InterruptedException ie)
{
}
}
while (ch != 'Z');
System.out.println();
done.countDown();
}
}

class Producer implements Runnable


{
private BlockingQueue<Character> queue;
private CountDownLatch done;

public Producer(BlockingQueue<Character> queue, CountDownLatch done)


{
this.queue = queue;
this.done = done;
}

public void run()


{
for (char ch = 'A'; ch <= 'Z'; ++ch)
{
try
{
queue.put(ch);
}

91
91
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools

catch (InterruptedException ie)


{
}
}
done.countDown();
}
}

The
The code
code is
is self-explanatory,
self-explanatory, but
but you
you need
need to
to note
note how
how to
to create
create aa BlockingQueue
BlockingQueue as
as an
an
object of the type ArrayBlockingQueue with space for 26 elements. Also note
object of the type ArrayBlockingQueue with space for 26 elements. Also note that the that the
program uses aa CountDownLatch
program uses CountDownLatch to to control
control when
when the
the executor
executor object
object can
can be
be shut
shut down,
down,
so the program terminates.
so the program terminates.

The
The class
class ConcurrentHashMap
ConcurrentHashMap is is used
used basically
basically in
in the
the same
same wayway as as aa HashMap,
HashMap, but but it
it is
is
extended with new thread safe methods, but without locking the entire data
extended with new thread safe methods, but without locking the entire data structure. One structure. One
of
of these
these methods
methods is is putIfAbsent(),
putIfAbsent(), which
which adds
adds aa new
new key/value
key/value pairs,
pairs, ifif there
there is
is not
not already
already aa
value
value with
with the
the same
same key.
key. It
It is
is thus
thus an alternative to
an alternative to the
the first
first performing
performing containsKey(),
containsKey(), and
and
then put(), but such that the operation is indivisible. The method remove()
then put(), but such that the operation is indivisible. The method remove() works in much works in much
the
the same
same way,
way, and
and there
there is
is also
also added
added aa replace()
replace() method.
method. In In fact,
fact, the
the class
class expanded
expanded by by
more than 30 methods, including to provide support fort lambda expressions
more than 30 methods, including to provide support fort lambda expressions and aggregate and aggregate
operations.
operations. All
All these
these changes
changes mean
mean that
that aa ConcurrentHashMap
ConcurrentHashMap is is suitable
suitable asas aa data
data structure
structure
into a cache memory.
into a cache memory.

EXERCISE
EXERCISE 11
11
The
The subject
subject of
of this
this exercise
exercise is
is to
to test
test the
the class
class ConcurrentHashMap. Create aa new
ConcurrentHashMap. Create new project,
project,
that you can call MapProgram. You
that you can call MapProgram. You must must add the following class:
add the following class:

class Worker implements Runnable


{
public static enum OPERATION { ADD, REP, REM }
private final ConcurrentMap<String, BigInteger> map; // ConcurrentHashMap
private final CountDownLatch done; // when the thread is finish
private String key; // key value, two upper case letters
private OPERATION opr; // the operation, to be performed

public Worker(ConcurrentMap<String, BigInteger> map, CountDownLatch done,


String key, OPERATION opr)
{
this.map = map;
this.done = done;
this.key = key;
this.opr = opr;
}

92
92
92
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Concurrencytools
ConCurrenCy Tools

public void run()


{
// The method should using the method sum
() determine a BigInteger for a
// large random n
// The method should then decided of opr add, change, or delete an item in
// the map
// finally, the method must print the result of the operation and
// counting done down
}

private BigInteger sum(int n)


{
// determines and returns the sum of the numbers from 1 through n when the
// sum is to be determined by add the numbers of the type BigInteger
// meaning is that the operation must take time
}
}

93%
OF MIM STUDENTS ARE
WORKING IN THEIR SECTOR 3 MONTHS
FOLLOWING GRADUATION

MASTER IN MANAGEMENT
• STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES
Length: 1O MONTHS
THAT THE CAPITAL OF SPAIN OFFERS
Av. Experience: 1 YEAR
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
Language: ENGLISH / SPANISH
PROFESSIONAL GOALS
Format: FULL-TIME
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
Intakes: SEPT / FEB
EXPERIENCE

5 Specializations #10 WORLDWIDE 55 Nationalities


MASTER IN MANAGEMENT
Personalize your program FINANCIAL TIMES
in class

www.ie.edu/master-management mim.admissions@ie.edu Follow us on IE MIM Experience

93
93
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
The program must then be written as follows:
The program must then be written as follows:
The program must then be written as follows:
public class MapProgram
{
public class MapProgram
{public static final Random rand = new Random();
private static final int N = 2; // number of threads
public static final Random rand = new Random();
private static final int M = 5; // number of operations
private static final int N = 2; // number of threads
private static final int M = 5; // number of operations
public static void main(String[] args)
{
public static void main(String[] args)
{ CountDownLatch done = new CountDownLatch(M);
ConcurrentMap<String,
CountDownLatch done = BigInteger> map = new ConcurrentHashMap();
new CountDownLatch(M);
ExecutorService executor
ConcurrentMap<String, = Executors.newFixedThreadPool(N);
BigInteger> map = new ConcurrentHashMap();
for (int i = 0; executor
ExecutorService i < M; ++i)
= Executors.newFixedThreadPool(N);
executor.submit(new
for Worker(map,
(int i = 0; i < M; ++i) done, createKey(), operation()));
// wait for done to be
executor.submit(new count downdone, createKey(), operation()));
Worker(map,
executor.shutdown();
// wait for done to be count down
} executor.shutdown();
}
private static Worker.OPERATION operation()
{
private static Worker.OPERATION operation()
{ // returns a random operation
} // returns a random operation
}
private static String createKey()
{
private static String createKey()
{ // creates a random key that is two upper case letters
} // creates a random key that is two upper case letters
}
}
}
When you are finished you can experiment and explore what happens if you change the
When you are finished you can experiment and explore what happens if you change the
When
numberyouof are finished (the
operations you constant
can experiment andif explore
M), and what the
you change happens if you
number of change the
concurrent
number of operations (the constant M), and if you change the number of concurrent
number of operations
threads (constant N). An(theexample
constant
of M), and the
running if you changewhich
program, the number of concurrent
has 5 threads and 15
threads (constant N). An example of running the program, which has 5 threads and 15
threads (constant
operations N). An example of running the program, which has 5 threads and 15
could be:
operations could be:
operations could be:
REM: TF is not found
REP:
REM: XN
TF is not found
REP: NV
XN is not found
REM:
REP: JG
NV is not found
REP:
REM: GS
JG is not found
REM:
REP: EM
GS is not found
REP:
REM: BC
EM is not found
ADD: DO sum(13340927) = 88990173280128
REP: BC is not found
ADD: MA sum(12188689) = 74282075863705
ADD: DO sum(13340927) = 88990173280128
ADD: MA sum(12188689) = 74282075863705

94

94
94
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools

REP: MC is not found


REP: LZ is not found
ADD: HW sum(11880594) = 70574262836715
REP: JP is not found
ADD: HK sum(14162771) = 100292048280606
REP: UJ is not found

8.10 PARALLELISM
8.10 PARALLELISM
The goal of multithreaded applications is parallelism, where several methods are performed
at the same time on the machine, or at least it seems for us users as if it was the case when
the individual threads in turn is running on the CPU in a very short period of time. That
is the way, at least if the machine only has a single processor, but today most machines
have more processors in the form of CPUs with multiple cores. Therefore such machines
has the opportunity for true parallelism, where multiple threads run at the same time, each
on their core. The basic primitives for threads, and also the concurrency tools discussed
above, however, are not very effective to use multiple cores or processors. For it really to
be possible, the task must be parallels and thus could be divided into smaller tasks that
can be performed independent of each other and to finish be assembling to the finished
result. This is far from everything, but there are also tasks that can be easily parallels. To
support that Java has a framework, called the Fork/Join that exactly supports the resolution
of these kinds of tasks.

Fork/Join consists of a special executor service and a thread pool, and each task is of the
framework split into smaller pieces that are forked to a thread from the thread pool. A task
waits until the subtasks are completed and result of each sub-task can be merged (joined)
for the final result. This process is also recursive, where subtasks in turn can be divided into
subtasks. The framework basically consists of the following classes:

1.
1. ForkJoinPool
2.
2. ForkJoinTask
3.
3. ForkJoinWorkerThread
4.
4. RecursiveAction
5.
5. RecursiveTask
6.
6. CountedCompleter.

95

95
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools

Consider as an example the following program:


Consider as an example the following program:
package thread26;

public class Thread26


{
private static int[][] A1 = { { 1, 2, 3 }, { 4, 5, 6} };
private static int[][] A2 = { { 1, 2, 3 }, { 4, 5, 6}, { 7, 8, 9 } };

public static void main(String[] args)


{
Matrix A = new Matrix(A1);
print(A);
Matrix B = new Matrix(A2);
print(B);
print(mul(A, B));
}

public static Matrix mul(Matrix A, Matrix B)


{
if (A.getCols() != B.getRows())
throw new IllegalArgumentException("Ulovlig matrixmultiplikation");
Matrix C = new Matrix(A.getRows(), B.getCols());

96

96
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS Concurrency
ConCurrenCy Tools
tools

for (int i = 0; i < A.getRows(); ++i)


for (int j = 0; j < B.getCols(); ++j)
for (int k = 0; k < A.getCols(); ++k)
C.setValue(i, j, C.getValue(i, j) + A.getValue(i, k) * B.getValue(k, j));
return C;
}

public static void print(Matrix M)


{
for (int i = 0; i < M.getRows(); ++i)
{
for (int j = 0; j < M.getCols(); j++)
System.out.printf("%5d", M.getValue(i, j));
System.out.println();
}
System.out.println();
}
}

class Matrix
{
private final int[][] matrix;

public Matrix(int rows, int cols)


{
matrix = new int[rows][cols];
}

public Matrix(int[][] array)


{
matrix = array;
}

public int getCols()


{
return matrix[0].length;
}

public int getRows()


{
return matrix.length;
}

public int getValue(int row, int col)


{
return matrix[row][col];
}

97 97
JAVA
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools
JAVA8:MULTITHREADED
8:MULTITHREADEDPROGRAMS
PROGRAMS ConCurrenCy
Concurrencytools
Tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools

public
public void
void setValue(int
setValue(int row,
row, int
int col,
col, int
int value)
value)
public
{{ void setValue(int row, int col, int value)
{ matrix[row][col] = value;
matrix[row][col] = value;
}}matrix[row][col] = value;
}}}
}

Here
Here is the class Matrix a simple matrix class (with int coordinates), and it is not much
Hereisisisthe
Here
the class
theclass Matrix
Matrixaaasimple
classMatrix simple matrix
simplematrix class
matrixclass (with
class(with
(withintint coordinates),
intcoordinates), and
anditititisisisnot
coordinates),and not much
notmuch
much
more
more than
than aa thin
thin encapsulation
encapsulation of
of aa 22 dimensional
dimensional array.
array. The
The program
program creates
creates two
two matrices
matrices
morethan
more thanaathin thinencapsulation
encapsulationofofaa22dimensional
dimensionalarray. array.The Theprogram
programcreates
createstwo twomatrices
matrices
and
and prints
prints them.
them. One
One isis aa 2×3
2×3 matrix,
matrix, and
and the
the second
second isis aa 3×3
3×3 matrix.
matrix. Therefore,
Therefore, you
you can
can
andprints
and printsthem.them.One Oneisisaa2×3 2×3matrix,
matrix,and andthe thesecond
secondisisaa3×3 3×3matrix.
matrix.Therefore,
Therefore,you youcan
can
compute
compute the
the two
two matrices
matrices product
product (the
(the first
first matrix
matrix has
has the
the same
same number
number ofof columns
columns as
as
computethe
compute thetwo twomatrices
matricesproductproduct(the (thefirst
firstmatrix
matrixhas hasthe thesame
samenumber
numberof ofcolumns
columnsas as
the
the second
second matrix
matrix has
has rows),
rows), and
and that’s
that’s exactly
exactly what
what method
method mul()
mul() does.
does. If
If you
you executes
executes
thesecond
the secondmatrix matrixhas hasrows),
rows),and andthat’s
that’sexactly
exactlywhatwhatmethod
methodmul() mul()does.
does.IfIfyou youexecutes
executes
the
the program,
program, you
you get
get the
the following
following result:
result:
theprogram,
the program,you youget
getthe
thefollowing
followingresult:
result:

11 22 33
1
4 2
5 3
6
4 5 6
4 5 6

11 22 33
1
4 2
5 3
6
4 5 6
4
7 5
8 6
9
7 8 9
7 8 9

30
30 36
36 42
42
30
66 36
81 42
96
66 81 96
66 81 96
The program is carried out in a single thread (the primay thread), but if you consider the
The
The program
program isis carried
carried out
out inin aa single
single thread
thread (the
(the primay
primay thread),
thread), but
but ifif you
you consider
consider the
the
method
The mul(),
program then
is carried you
outcan
in also writethread
a single it as follows:
(the primay thread), but if you consider the
method
method mul(),
mul(), then
then you
you can
can also
also write
write itit as
as follows:
follows:
method mul(), then you can also write it as follows:
public
public static
static Matrix
Matrix mul(Matrix
mul(Matrix A,A, Matrix
Matrix B)B)
public
{{ static Matrix mul(Matrix A, Matrix B)
{if (A.getCols() != B.getRows())
if (A.getCols() != B.getRows())
ifthrow
(A.getCols() != B.getRows())
throw new
new IllegalArgumentException("Ulovlig
IllegalArgumentException("Ulovlig matrixmultiplikation");
matrixmultiplikation");
throw
Matrix new
C = IllegalArgumentException("Ulovlig
new Matrix(A.getRows(), matrixmultiplikation");
B.getCols());
Matrix C = new Matrix(A.getRows(), B.getCols());
Matrix
for C = new Matrix(A.getRows(), B.getCols());
for (int
(int ii == 0;0; ii << A.getRows();
A.getRows(); ++i)
++i) mul(A,
mul(A, B,B, C,
C, i);
i);
for (int
return C; i = 0; i < A.getRows(); ++i) mul(A, B, C, i);
return C;
}}return C;
}
public
public static
static voidvoid mul(Matrix
mul(Matrix A,A, Matrix
Matrix B,B, Matrix
Matrix C,
C, int
int r)r)
public
{{ static void mul(Matrix A, Matrix B, Matrix C, int r)
{for (int j = 0; j < B.getCols(); ++j)
for (int j = 0; j < B.getCols(); ++j)
for
for(int j k= =0;0;j k< <B.getCols(); ++j)
for (int
(int k = 0; k < A.getCols();
A.getCols(); ++k)
++k)
for (int k
C.setValue(r, = 0; k < A.getCols(); ++k)
C.setValue(r, j, C.getValue(r, j) ++ A.getValue(r,
j, C.getValue(r, j) A.getValue(r, k) k) ** B.getValue(k,
B.getValue(k, j));
j));
}} C.setValue(r, j, C.getValue(r, j) + A.getValue(r, k) * B.getValue(k, j));
}

98
98
98
98
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools

Thismeans
This meansthatthatthethematrix
matrixmultiplication
multiplicationisisdivided
dividedinto
intosub-tasks,
sub-tasks,wherewherethere
thereisisaasubtask
subtask
for each
for each row
row inin the
the first
first matrix.
matrix. Each
Each ofof these
these sub-tasks
sub-tasks are
are actually
actually independent
independent of of each
each
other and
other and cancan therefore
therefore be be performed
performed in in separate
separate thread,
thread, and
and ifif you
you can
can maintain
maintain that
that the
the
threads are
threads are executed
executed on on their
their own
own processor,
processor, oneone would
would expect
expect an an improved
improved efficiency.
efficiency.
Not in
Not in this
this case,
case, where
where there
there are
are few
few rows
rows and
and columns,
columns, butbut for
for large
large matrices,
matrices, the
the matrix
matrix
multiplication isis actually
multiplication actually anan extensive
extensive operation
operation with
with aa bad
bad time
time complexity.
complexity.

The task
The task isis thus
thus an
an example
example of of aa job
job where
where you
you can
can experiment
experiment with with Fork/Join
Fork/Join what
what the
the
following program
following program does
does (I(I have
have not
not shown
shown the
the class
class Matrix,
Matrix, asas itit isis the
the same
same asas above):
above):

package thread27;

import java.util.*;
import java.util.concurrent.*;

public class Thread27 extends RecursiveAction


{
private static int[][] A1 = { { 1, 2, 3 }, { 4, 5, 6} };
private static int[][] A2 = { { 1, 2, 3 }, { 4, 5, 6}, { 7, 8, 9 } };

Excellent Economics and Business programmes at:

“The perfect start


of a successful,
international career.”

CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www.rug.nl/feb/education

99
99
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS Concurrency
ConCurrenCy Tools
tools

public static void main(String[] args)


{
Matrix A = new Matrix(A1);
print(A);
Matrix B = new Matrix(A2);
print(B);
Matrix C = new Matrix(A.getRows(), B.getCols());
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(new Thread27(A, B, C));
print(C);
}

private final Matrix A, B, C;


private final int row;

public Thread27(Matrix A, Matrix B, Matrix C)


{
this(A, B, C, -1);
}

public Thread27(Matrix A, Matrix B, Matrix C, int row)


{
if (A.getCols() != B.getRows())
throw new IllegalArgumentException("Ulovlig matrixmultiplikation");
this.A = A;
this.B = B;
this.C = C;
this.row = row;
}

public void compute()


{
if (row == -1)
{
List<Thread27> tasks = new ArrayList();
for (int r = 0; r < A.getRows(); ++r) tasks.add(new Thread27(A, B, C, r));
invokeAll(tasks);
}
else mul(A, B, C, row);
}

public static void mul(Matrix A, Matrix B, Matrix C, int r)


{
for (int j = 0; j < B.getCols(); ++j)
for (int k = 0; k < A.getCols(); ++k)
C.setValue(r, j, C.getValue(r, j) + A.getValue(r, k) * B.getValue(k, j));
}

100100
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools
JAVA
JAVA 8:MULTITHREADED PROGRAMS
8:MULTITHREADED PROGRAMS ConCurrenCy
ConCurrenCy tools
tools
public static void print(Matrix M)
{public static void print(Matrix M)
public
public static
static void
void print(Matrix
print(Matrix M)
M)
{for (int i = 0; i < M.getRows(); ++i)
{
{
{for (int i = 0; i < M.getRows(); ++i)
for
for (int
(int i
i == 0;
0; i
i << M.getRows();
M.getRows(); ++i)
++i)
{for (int j = 0; j < M.getCols(); j++)
{
{
for (int j = 0; j < M.getCols();
System.out.printf("%5d", j++) j));
M.getValue(i,
for
for (int
(int jj =
= 0;
0; jj <
< M.getCols();
M.getCols(); j++)
j++)
System.out.printf("%5d", M.getValue(i, j));
System.out.println();
System.out.printf("%5d",
System.out.printf("%5d", M.getValue(i,
M.getValue(i, j));
j));
} System.out.println();
System.out.println();
System.out.println();
}
System.out.println();
}
}
} System.out.println();
System.out.println();
System.out.println();
}}
}
}
}
}
}
The
Theprogram
programisistechnical,
technical,and andthethefollowing
followingpoints pointsonlyonlyatatthe
themost
mostcentral.
central.IfIfaatask task––aa
The
class program
––must is technical, and the following points only at the most central. If a task –a
The mustbe
classprogram is parallels,
be parallels,itit
technical, must
and theinherits
must following
inherits the class
classRecursiveAction,
thepoints only at the most
RecursiveAction, which isisthe
central.
which If aclass
the taskthat
class –a
that
class – must
contains the be parallels,
whole secret. it The
mustclass
inherits
is the class
abstract and RecursiveAction,
has an which
abstract method is thecompute(),
class that
class
contains– mustthe be parallels,
whole it must
secret. inherits
The class the classand
is abstract RecursiveAction,
has an abstract which is the compute(),
method class that
contains
and the whole secret. The class is abstract and has an abstract method compute(),
andititisisthere
contains the that
thatthe
therewhole interesting
secret.
the The class
interesting thing is is,
thing is,seen
seenfrom
abstract and the
from theprogrammer.
has an The
Theclass
abstract method
programmer. class has
hastwo
compute(),two
and it is
constructors, there that
that is the interesting
used, respectivelything by is, seen
three from the
matrices, programmer.
and three The
matrices class
and has
a two
row
and it is therethat
constructors, that istheused,
interesting thing by
respectively is, three
seen from the programmer.
matrices, The class
and three matrices andhasa tworow
constructors,
number. The that is used,dorespectively
constructors nothing but byinitialize
three matrices,
the and three instance
corresponding matricesvariables.
and a row IfIf
constructors,
number. The that is used, do
constructors respectively
nothing but by initialize
three matrices, and three matrices
the corresponding and a row
instance variables.
number.
you Thetheconstructors do nothing but totoinitialize the corresponding instance variables. If
youlook
number.lookatThe
at the main()
main()method,
constructors ititstarts
do nothing
method, but
starts create
createthe
initialize matrices,
the
the but
butthen
corresponding
matrices, ititcreates
instance
then aathread
variables.
creates threadIf
you
pool look
tototheat the main() method, it starts to create the matrices, but then it creates a thread
you
poollook at Fork/Join:
the the main() method, it starts to create the matrices, but then it creates a thread
Fork/Join:
pool to the Fork/Join:
pool to the Fork/Join:
ForkJoinPool pool = new ForkJoinPool();
ForkJoinPool pool = new ForkJoinPool();
ForkJoinPool
ForkJoinPool pool
pool =
= new
new ForkJoinPool();
ForkJoinPool();
It is subsequently used to create a RecursiveAction object (the task) and assign it to the
It is object:
pool subsequently used to create a RecursiveAction object (the task) and assign it to the
ItIt isis subsequently
subsequently used
used to
to create
create aa RecursiveAction
RecursiveAction object
object (the
(the task)
task) and
and assign
assign itit to
to the
the
pool object:
pool
pool object:
object:
pool.invoke(new Thread27(A, B, C));
pool.invoke(new Thread27(A, B, C));
pool.invoke(new
pool.invoke(new Thread27(A,
Thread27(A, B, C));
B, C));
The result of this is that the method compute() is performed. If the instance variable row
Thethe
has result of -1
value this is that
(and thethemethod
it has compute()
first time), is performed.
then the task is splitIf the ainstance variable row
The
The result
result of
of this
this isis that
that the
the method
method compute()
compute() isis performed.
performed. IfIfinto
the list of tasks,
the instance
instance which
variable
variable row
row
has the
parallels value
with -1
the (and it
statement has the first time), then the task is split into a list of tasks, which
has
has the
the value
value -1-1 (and
(and itit has
has the
the first
first time),
time), then
then the
the task
task isis split
split into
into aa list
list of
of tasks,
tasks, which
which
parallels with the statement
parallels
parallels with
with the
the statement
statement
invokeAll(tasks);
invokeAll(tasks);
invokeAll(tasks);
invokeAll(tasks);
If the row not is -1, then instead the method mul() is called, which performs the matrix
If the row notfor
multiplication is -1, then row.
instead theprogram
methodis mul() is called, which performs
resultthe matrix
IfIf the
the row not isisa-1,
row not specific
-1, then If the
then instead
instead the
the method performed,
method mul() you get
mul() isis called,
called, the same
which
which performs
performs theas above.
the matrix
matrix
multiplication for a specific row. If the program is performed, you get the same result as above.
multiplication
multiplicationfor foraaspecific
specificrow.
row.IfIfthe
theprogram
programisisperformed,
performed,you youget
getthe
thesame
sameresult
resultasasabove.
above.

101
101
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools

EXERCISE 12
Create a new project, that you can call Matrices1. The project should be substantially a
copy of the project Thread26, and thus a program that can calculate the product of two
matrices, but it should this time be larger matrices. Start by adding a method that can create
a matrix with a given number of rows and columns and initialize the matrix with random
one-digit integers. You can then test the program with 1000×2000 and 2000×1000 matrices.
You can not print the matrices (that do not really make sense with such large matrices),
but you should instead measure and print how long time the matrix multiplication takes.
Remember only to measure the time for the matrix multiplication.

You must then create a similar project that you can call Matrices2, but this time the program
should work in the same way as the program Thread27 where the matrix multiplication
should be parallels. Try to observe a time difference between the two programs. That should
be able, if your machine has a multicore processor.

American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

▶▶ enroll by September 30th, 2014 and


▶▶ save up to 16% on the tuition!
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

102
JAVA 8:MULTITHREADED PROGRAMS ConCurrenCy tools
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools

8.11 COMPLETIONSERVICE
8.11 COMPLETIONSERVICE
As the last synchronization tool I’ll mention a CompletionService, which is an interface that
As the last synchronization tool I’ll mention a CompletionService, which is an interface that
defines a service that detaches the creation of an asynchronous tasks from the handling of
defines a service that detaches the creation of an asynchronous tasks from the handling of
the result. The idea is that a producer uses submit() to start callable objects in a thread, and
the result. The idea is that a producer uses submit() to start callable objects in a thread, and
a consumer can call a blocking take() method that is waiting for the result.
a consumer can call a blocking take() method that is waiting for the result.

package thread28;

import java.math.*;
import java.util.concurrent.*;

public class Thread28


{
private static final int N = 10;

public static void main(String[] args) throws Exception


{
ExecutorService executor = Executors.newFixedThreadPool(N);
CompletionService<BigDecimal> completion =
new ExecutorCompletionService<BigDecimal>(executor);
Future<BigDecimal>[] res = new Future[N];
for (int i = 0, n = 100; i < N; ++i, n += 100)
{
res[i] = completion.submit(new ECalculator(n));
completion.take();
}
for (int i = 0; i < res.length; ++i) System.out.println(res[i].get());
executor.shutdown();
}
}

class ECalculator implements Callable<BigDecimal>


{
private final int dec;

public ECalculator(int dec)


{
this.dec = dec;
}

public BigDecimal call()


{
MathContext mc = new MathContext(dec, RoundingMode.HALF_UP);
BigDecimal y = BigDecimal.ZERO;

103
103
JAVA 8:MULTITHREADED PROGRAMS Concurrency Tools
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS ConCurrenCy
ConCurrenCy tools
tools

for
for (int
(int ii =
= 0;
0; ;
; ++i)
++i)
{
{

BigDecimal fac = BigDecimal.ONE.divide(factorial(new BigDecimal(i)), mc);
BigDecimal fac = BigDecimal.ONE.divide(factorial(new BigDecimal(i)), mc);
BigDecimal
BigDecimal z z =
= y.add(fac,
y.add(fac, mc);
mc);
if
if (z.compareTo(y)
(z.compareTo(y) ==
== 0)
0) break;
break;
y
y == z;
z;
}
}
System.out.println("Finish");
System.out.println("Finish");
return
return y;y;
}
}

private
private BigDecimal
BigDecimal factorial(BigDecimal
factorial(BigDecimal n)
n)
{
{

return n.equals(BigDecimal.ZERO) ?
return n.equals(BigDecimal.ZERO) ?

BigDecimal.ONE : n.multiply(factorial(n. subtract(BigDecimal.ONE)));
BigDecimal.ONE : n.multiply(factorial(n. subtract(BigDecimal.ONE)));
}
}
}
}

In
InIn the
the above
the above program,
above program, the
program, the class
the class ECalculator
class ECalculator is
ECalculator isis the
the same
the same as
same asas III have
have used
have used before
used before –
before –– with
with only
with only
only
one
one difference
one difference that
difference that the
that the method
the method call()
method call() prints
call() prints a text
prints aa text before
text before it returns
before itit returns the
returns the result.
the result. The
result. The goal
goal is
The goal isis
to
to show
to show that
show that all
that all threads
all threads are
threads are performed
are performed before
performed before the
before the result
the result is printed.
result isis printed. In
printed. In main()
In main() is created
main() isis created as
created asas
usual
usual an
usualan ExecutorService
anExecutorService object,
ExecutorServiceobject, but
object,but ititis
butit isisencapsulated
encapsulated
encapsulatedin ininaaaCompletionService
CompletionService
CompletionServiceobject. object. Then
object.Then are
Thenareare
started
started 10
started10 threads
10threads
threadson on basis
onbasis of a Callable
basisofofaaCallable object
Callableobject
objectso so that
sothat each
thateach thread
eachthread determines
threaddetermines
determinesthe the number
thenumber
number
eee with
with a number
with aa number of decimal
number ofof decimal places
decimal places (a time-consuming
places (a(a time-consuming operation),
time-consuming operation),
operation), and and for
and for each
for each thread
thread is
each thread isis
performed
performed
performedthe the statement:
thestatement:
statement:

completion.take();
completion.take();

This
Thismeans
This meansthat
means thatthe
that theprimary
the primarythread
primary threadwaits
thread waitsuntil
waits untilthe
until the10
the 10worker
10 workerthreads
worker threadsare
threads arecompleted.
are completed.
completed.

104
104
104
JAVA 8:MULTITHREADED PROGRAMS Atomic variabler

9 ATOMIC VARIABLER
Finally, I will mention some classes that can be used to ensure mutual exclusion of operations
on simple variables, but without the need to ensure the code using locks which generally
cost performance. In fact, several simple operations on variables of primitive types is not
thread safe, but consist of more operations and thus can be interrupted. The classes are in

java.util.concurrent.atomic

and the main classes are

-- AtomicBoolean
-- AtomicInteger
-- AtomicIntegerArray
-- AtomicLong
-- AtomicLongArray
-- AtomicReference
-- AtomicReferenceArray
-- DoubleAccumulator

105
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS atomIC
Atomic varIabler
variabler
JAVA 8:MULTITHREADED PROGRAMS atomIC varIabler

--- DoubleAdder
DoubleAdder
- DoubleAdder
--- LongAccumulator
LongAccumulator
- LongAccumulator
--- LongAdder
LongAdder
- LongAdder

If,
If, for
for example
example you
you need
need to
to implement
implement aa class
class that
that generates
generates aa continuous
continuous id,
id, you
you will
will
If, for example you need to implement a class that generates a continuous id, you will
typically write something like the following:
typically write something like the following:
typically write something like the following:
class ID
class
{ ID
{private static volatile long ID = 1;
private static volatile long ID = 1;

public static synchronized long getID()


public
{ static synchronized long getID()
{ return ID++;
} return ID++;
}}
}

where the method getID() is synchronized, since the ++ operation is not thread safe. Such
where the method getID() is synchronized, since the ++ operation is not thread safe. Such
a solution works and will also in most contexts be fine enough, but every time you need
a solution works and will also in most contexts be fine enough, but every time you need
a new id, you set a lock and that is not free. However, you can write the class as follows:
a new id, you set a lock and that is not free. However, you can write the class as follows:
import java.util.concurrent.atomic.*;
import java.util.concurrent.atomic.*;

class ID
class
{ ID
{private static AtomicLong ID = new AtomicLong(1);
private static AtomicLong ID = new AtomicLong(1);

static long getID()


static
{ long getID()
{ return ID.getAndIncrement();
} return ID.getAndIncrement();
}}
}

Here are getID() also thread safe, but the method is significantly more efficient, as there is
Here are
Here are getID()
getID() also
also thread
thread safe,
safe, but
but the
the method
method isis significantly
significantly more
more efficient,
efficient, as
as there
there is
is
not set a lock. AtomicLong is a class that encapsulates a long and has a number of methods
not set
not set aa lock.
lock. AtomicLong
AtomicLong is
is aa class
class that
that encapsulates
encapsulates aa long
long and
and has
has aa number
number ofof methods
methods
that perform the usual operations on a long, but such they are thread safe.
that perform
that perform the
the usual
usual operations
operations onon aa long,
long, but
but such
such they
they are
are thread
thread safe.
safe.

106
106
106
JAVA 8:MULTITHREADED PROGRAMS Swing

10 SWING
If you have a GUI application, threads generally can create problems, where the user interface
is not updated correctly, and maybe you even get an exception. In this section I will show
how to use threads within an application written using swing.

Swing is single-threaded, and if you do nothing else, what is the case in all the GUI
programs in this book until this place, where it happens all in a single thread. The thread
that renders the graphics (windows and components), that also deal with events, is called
the event dispatcher thread and is commonly referred to as EDT. This thread processes
all events that come from the underlying event queue and calls the component’s event
handlers, so they are performed by EDT. This means that everything regarding drawing in
the window must takes place in this thread. This also means that to be sure that a Swing
program works correctly, you have to be careful how the program’s code interacts with the
EDT, and especially pay attention to

1. that it is always EDT, that creates GUI components


2. that you not must perform code that slows EDT

Since Swing is single-threaded, should a Swing program always create the GUI part in the
EDT thread and never create components in another thread, nor in the primary thread. Most
Swing components and including JFrame is not thread safe, and use these components from
a different thread than EDT, there is a risk that the user interface is not updated correctly.

To explain a little of all that, I will show a program that will open the following window,
which has a list box and a button:

107
JAVA 8:MULTITHREADED PROGRAMS Swing

If you click the button, you get a dialog box where you have to select the file with zip
codes (which I have used several times):

108
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS swIng
Swing

and
and opens
opens this
this file
file the
the zip
zip codes
codes appears
appears in
in the
the main
main window’s
window’s list
list box.
box. The
The code
code for
for the
the
main window are as follows:
main window are as follows:

package thread29;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.io.*;

public class MainView extends JFrame


{
private DefaultListModel model = new DefaultListModel();
private JButton cmd = new JButton("Opdater");

public MainView()
{
super("Thread29");
setSize(300, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createView();
setVisible(true);
}

private void createView()


{
JPanel bottom = new JPanel(new FlowLayout(FlowLayout.RIGHT));
cmd.addActionListener(this::update);
bottom.add(cmd);
JPanel panel = new JPanel(new BorderLayout(0, 20));
panel.setBorder(new EmptyBorder(20, 20, 20, 20));
panel.add(new JScrollPane(new JList(model)));
panel.add(bottom, BorderLayout.SOUTH);
add(panel);
JOptionPane.showMessageDialog(this, Thread.currentThread().getId());
}

public void update(ActionEvent e)


{
JOptionPane.showMessageDialog(this, Thread.currentThread().getId());
final JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{

109
109
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Swing
swIng

update(chooser.getSelectedFile());
cmd.setEnabled(false);
}
}

private void update(File file)


{
try
{
BufferedReader reader = new BufferedReader(new FileReader(file));
for (String line = reader.readLine(); line != null; line = reader.readLine())
{
String[] elem = line.split(";");
if (elem.length == 2) model.addElement(elem[0] + " " + elem[1]);
busy();
}
reader.close();
}
catch (Exception ex)
{
model.addElement(ex.toString());
}
}

private void busy()


{
for (int i = 0; i < 500000; ++i) Math.cos(Math.sqrt(Math.PI));
}
}

and
and itit contains
contains nothing
nothing new,
new, butbut aa couple
couple of
of the
the statements
statements require
require an
an explanation.
explanation. The The
last method busy() is a dummy method and is a method that requires some
last method busy() is a dummy method and is a method that requires some time. It is used time. It is used
in
in the
the method
method update(),
update(), which
which isis the
the method
method that
that reads
reads the
the file
file with
with zip
zip codes
codes where
where itit isis
carried
carriedoutoutevery
everytimetimethere
thereisisread
readaaline
linein
inthe
thefile.
file.The
Theconsequence
consequenceisisthatthatitittakes
takesaalong
long
time
timeto toupdate
updatethethelist
listbox.
box.The
Themethod
methodupdate(),
update(),which
whichisiscalled
calledfrom
fromthe
theevent
eventhandler
handlerfor for
the button, that start by displaying a message box that shows the id of the
the button, that start by displaying a message box that shows the id of the current thread. current thread.
Similarly,
Similarly, the
the last
last statement
statement in in the
the method
method createView()
createView() displays
displays aa message
message box
box that
that shows
shows
the
the current
current thread
thread id.id.

110
110
JAVA 8:MULTITHREADED PROGRAMS swIng
JAVA 8:MULTITHREADED PROGRAMS Swing

The main() method is the following:


The main() method is the following:
package thread29;

public class Thread29


{
public static void main(String[] args)
{
javax.swing.JOptionPane.showMessageDialog(null,
Thread.currentThread().getId());
new MainView();
}
}

and
and here
here isis nothing
nothing newnew beyond
beyond that
that itit also
also starts
starts to
to show
show aa message
message box
box with
with the
the id
id of
of
the
the current
current thread.
thread. IfIf you
you now
now run
run the
the program,
program, youyou first
first get
get aa message
message box:
box:

Join the best at Top master’s programmes


• 3 3rd place Financial Times worldwide ranking: MSc
the Maastricht University International Business
• 1st place: MSc International Business
School of Business and • 1st place: MSc Financial Economics
• 2nd place: MSc Management of Learning

Economics! • 2nd place: MSc Economics


• 2nd place: MSc Econometrics and Operations Research
• 2nd place: MSc Global Supply Chain Management and
Change
Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012;
Financial Times Global Masters in Management ranking 2012

Maastricht
University is
the best specialist
university in the
Visit us and find out why we are the best! Netherlands
(Elsevier)
Master’s Open Day: 22 February 2014

www.mastersopenday.nl

111
111
JAVA 8:MULTITHREADED PROGRAMS Swing

which opens in the main() method. It tells that the message box is opened in the primary
thread (which was also to be expected). If you here click OK, you get the message box again:

but this time the message box is opened in the method createView() in the class MainView,
and it is still happened from the primary thread. That is that the window is created in the
primary thread. When you here click OK, the main window opens. Clicking on the button,
you get the following message box:

which is opened in the button’s event handler, and you can see that it happens in a different
thread. This is the event dispatcher thread, and if you click OK, you get chance to browse
the file, after which the list box is updated:

112
JAVA 8:MULTITHREADED PROGRAMS swIng
JAVA 8:MULTITHREADED PROGRAMS Swing

After you’ve accepted the file, it takes a relatively long time before the list box is updated, and
After you’ve accepted the file, it takes a relatively long time before the list box is updated, and
in that time the program does not respond. You can change the window size, but you will
in that time the program does not respond. You can change the window size, but you will
find that the window is not redrawn. It happens only when the event handler is completed.
find that the window is not redrawn. It happens only when the event handler is completed.
The program has – at least – two problems. First, it is carried out the code that creates the
The program has – at least – two problems. First, it is carried out the code that creates the
window and its components, and the event handler in the two different threads. As long as
window and its components, and the event handler in the two different threads. As long as
the program does not use other threads, it will probably not cause problems, but it is not
the program does not use other threads, it will probably not cause problems, but it is not
consistent with how a Swing program should be written. Second, the program has a time
consistent with how a Swing program should be written. Second, the program has a time
when it does not respond to user actions (here obviously unnecessarily long because of the
when it does not respond to user actions (here obviously unnecessarily long because of the
method busy()), but overall it is a requirement that a GUI application must react sensibly
method busy()), but overall it is a requirement that a GUI application must react sensibly
to the user’s interaction with the program.
to the user’s interaction with the program.

I would start by solving the first problem, and in the project Thread30 the main program
I would start by solving the first problem, and in the project Thread30 the main program
is the following:
is the following:
package thread30;

public class Thread30


{
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(() -> new MainView());
}
}

This means
This means that
that the
the window
window isis nownow created
created by
by the
the event
event dispatcher
dispatcher thread
thread –– the
the EDT
EDT
thread. The
thread. The class
class MainView
MainView isis unchanged
unchanged (except
(except another
another text
text in
in the
the title
title bar),
bar), and
and ifif you
you
run the
run the program,
program, youyou will
will see
see that
that the
the window
window isis created
created in
in the
the same
same thread
thread that
that performs
performs
the event
the event handler.
handler.

The class
The class SwingUtilities
SwingUtilities has
has aa number
number ofof static
static methods
methods that
that are
are used
used in
in aa variety
variety of
of contexts
contexts
in Swing.
in Swing. For
For threads
threads these
these are
are basically
basically of
of three
three methods:
methods:

1. invokeAndWait()
1. invokeAndWait() thatthat has
has aa Runnable
Runnable objet
objet as
as aa parameter
parameter and
and executes
executes the
the current
current
run() method
run() method in in the
the thread
thread EDT.
EDT. The
The method
method isis carried
carried out
out synchronism
synchronism withwith
EDT, and
EDT, and invokeAndWait()
invokeAndWait() blocks
blocks the
the current
current thread
thread until
until the
the EDT
EDT hashas processed
processed
all pending
all pending events.
events. invokeAndWait()
invokeAndWait() isis used
used when
when thethe program
program must
must update
update the
the UI
UI
from aa different
from different thread
thread than
than EDT.
EDT. This
This method
method should
should never
never bebe called
called from
from EDT.
EDT.

113
113
JAVA 8:MULTITHREADED PROGRAMS Swing

2. invokeLater() also has a Runnable object as a parameter, and performs the run()
method in EDT, but it happens asynchronously this time, and the run() method
is performed only after the EDT has processed pending events. invokeLater() is
used when an application wants to update the user interface, and the method can
be called from any thread.
3. isEventDispatchThread() is a method that returns true, if it is performed in EDT.

Looking at the above, the main() method defines (by means of a lambda expression) a Runnable
object to instantiate the main window. The object is used as a parameter to invokeLater(),
and the result is that it is the event dispatcher thread, which creates the window. Similar
to the above, it means that all the GUI programs that I so far have shown are not written
correctly, and although the programs have hardly any significance, I will continue writing
GUI applications as shown in the main() method above.

Then there’s the other problem with the program is not responding while it loads the zip
codes. It is clear that the problem must be solved by loading the zip codes in a worker
thread, but there is a little more, because you can be sure that the user interface is updated
correctly. The problem is solved in the project Thread31, and the only thing that has changed
are the following two methods:

114
JAVA 8:MULTITHREADED
JAVA 8:MULTITHREADED PROGRAMS
PROGRAMS Swing
swIng

public void opdater(ActionEvent e)


{
final JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
new Thread(() -> update(chooser.getSelectedFile())).start();
cmd.setEnabled(false);
}
}

private void update(File file)


{
try
{
BufferedReader reader = new BufferedReader(new FileReader(file));
for (String line = reader.readLine(); line != null; line = reader.readLine())
{
String[] elem = line.split(";");
if (elem.length == 2) SwingUtilities.invokeAndWait(
() -> model.addElement(elem[0] + " " + elem[1]));
busy();
}
reader.close();
}
catch (Exception ex)
{
model.addElement(ex.toString());
}
}

In
In the
the event
event handler
handler isis now
now started
started aa thread
thread which
which performs
performs thethe method
method update().
update(). ThisThis method
method
isis largely
largely unchanged,
unchanged, but but when
when thethe list
list box
box need
need toto be
be updated,
updated, itit must
must according
according to to the
the
above
above be be in
in EDT,
EDT, and
and whenwhen the
the update
update waswas carried
carried out
out inin aa runnable
runnable object
object itit isis performed
performed
by
by invokeAndWait()
invokeAndWait() andand thus
thus inin the
the thread
thread EDT.
EDT. InIn this
this case
case itit used
used invokeAndWait()
invokeAndWait() insteadinstead
of
of invokeLater(),
invokeLater(), but
but itit has
has hardly
hardly any
any meaning,
meaning, butbut invokeAndWait()
invokeAndWait() ensures
ensures that
that no no events
events
concerning
concerning something
something elseelse are
are hanging.
hanging.

If
If you
you try
try out
out the
the program
program Thread31
Thread31 you
you will
will find
find that
that the
the program
program now
now “is
“is in
in live”
live” while
while
the
the list
list box
box isis updated.
updated.

115
115
JAVA 8:MULTITHREADED PROGRAMS Swing
JAVA 8:MULTITHREADED PROGRAMS swIng

10.1 SWINGWORKER
10.1 SWINGWORKER
Sometimes there is a need to start a task that takes time (for example to load the zip codes
Sometimes there is a need to start a task that takes time (for example to load the zip codes
from a file), and to reduce the number of updates to the user interface, and only update the
from a file), and to reduce the number of updates to the user interface, and only update the
user interface at once, after the job is done. You can then use a class called SwingWorker.
user interface at once, after the job is done. You can then use a class called SwingWorker.
It is a generic class, as is parameterized with two parameters SwingWorker<T, V>. It is an
It is a generic class, as is parameterized with two parameters SwingWorker<T, V>. It is an
abstract class, and there is at least one method to be overridden. The first is
abstract class, and there is at least one method to be overridden. The first is

protected abstract T doInBackground()


protected abstract T doInBackground()

which is the method that performs the task for a worker thread, which returns a value of
which is the method that performs the task for a worker thread, which returns a value of
the first parameter type (if there is no return, specify the parameter type as Void ). When
the first parameter type (if there is no return, specify the parameter type as Void ). When
this method terminates, the following method is performed:
this method terminates, the following method is performed:

protected void done()


protected void done()

but such that it is performed in EDT, where you can safely update the user interface. The
but such that it is performed in EDT, where you can safely update the user interface. The
default implemntation performs nothing, and you will often override the method. While
default implemntation performs nothing, and you will often override the method. While
the task is performed, you can, if desired periodically update the user interface by overriding
the task is performed, you can, if desired periodically update the user interface by overriding
and call the method
and call the method

protected void process(List<V> chunks)


protected void process(List<V> chunks)

The class SwingWorker have additional two methods that you need to know:
The class SwingWorker have additional two methods that you need to know:

1. execute() starts a worker thread


1. execute() starts a worker thread
2. T get() waits to doInBackground() is terminated and returns the result
2. T get() waits to doInBackground() is terminated and returns the result

Below is how the program with the zip code must be changed if the list box should be
Below is how the program with the zip code must be changed if the list box should be
updated with a SwingWorker:
updated with a SwingWorker:

package thread32;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.io.*;
import java.util.*;

116
116
JAVA 8:MULTITHREADED PROGRAMS Swing
JAVA 8:MULTITHREADED PROGRAMS swIng

public class MainView extends JFrame


{
private DefaultListModel model = new DefaultListModel();
private JButton cmd = new JButton("Update");

public MainView()
{
super("Thread32");
setSize(300, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createView();
setVisible(true);
}

private void createView()


{
JPanel bottom = new JPanel(new FlowLayout(FlowLayout.RIGHT));
cmd.addActionListener(this::update);
bottom.add(cmd);
JPanel panel = new JPanel(new BorderLayout(0, 20));
panel.setBorder(new EmptyBorder(20, 20, 20, 20));
panel.add(new JScrollPane(new JList(model)));

Need help with your


dissertation?
Get in-depth feedback & advice from experts in your
topic area. Find out what you can do to improve
the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

117
117
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS Swing
swIng

panel.add(bottom, BorderLayout.SOUTH);
add(panel);
}

public void update(ActionEvent e)


{
final JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
new Zipcodes(chooser.getSelectedFile()).execute();
cmd.setEnabled(false);
}
}

class Zipcodes extends SwingWorker<ArrayList<String>, Void>


{
private final File file;

public Zipcodes(File file)


{
this.file = file;
}

public ArrayList<String> doInBackground()


{
ArrayList<String> list = new ArrayList();
try
{
BufferedReader reader = new BufferedReader(new FileReader(file));
for (String line = reader.readLine(); line != null;
line = reader.readLine())
{
String[] elem = line.split(";");
if (elem.length == 2) list.add(elem[0] + " " + elem[1]);
}
reader.close();
}
catch (Exception ex)
{
list.clear();
}
return list;
}

118
118
JAVA 8:MULTITHREADED
JAVA 8:MULTITHREADED PROGRAMS
PROGRAMS swIng
swIng
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS Swing
swIng

public void
public void done()
done()
public
{
{ void done()
{ try
try
try
{
{
{ ArrayList<String>
ArrayList<String> listlist = = get();
get();
ArrayList<String>
for (String line list
: =
list) get();
model.addElement(line);
for (String line : list) model.addElement(line);
for
}
} (String line : list) model.addElement(line);
} catch
catch (Exception
(Exception ex)
ex)
catch
{
{ (Exception ex)
{ model.clear();
model.clear();
model.clear();
}
}
}
}
}
}
}
}
}
}
}
}

The
Theimportant
importantthing
thingisisthe
theclass
classZipcodes,
Zipcodes,that
thatisisan
aninner
innerclass.
class.ItItinherits
inheritsthe
theclass
class
The important thing is the class Zipcodes, that is an inner class. It inherits the class
SwingWorker<ArrayList<String>, Void>
SwingWorker<ArrayList<String>, Void>
SwingWorker<ArrayList<String>, Void>

parameterized
parameterized by by aa single
single parameter
parameter (the
(the last
last should
should not not toto bebe used),
used), and
and thethe class
class must
must
parameterized
therefore by a single parameter (the last should not to be used), and the class must
therefore implement
implement the the method
method doInBackground(),
doInBackground(), which which isis the the code
code that
that performs
performs the the
therefore
worker implement
thread (a the
different method
thread doInBackground(),
than EDT). The which
method is the
reads code
the that
contents performs
of the filethe
and
worker thread (a different thread than EDT). The method reads the contents of the file and
worker thread (a different thread than EDT). The method reads the contents of the file and
saves
saves itit asas lines
lines inin aa ArrayList<String>,
ArrayList<String>, which
which thenthen isis the
the value
value that
that the
the method
method returns.
returns.
saves it as lines in a ArrayList<String>, which then is the value that the method returns.
Note
Note that
that II have
have removed
removed the the method
method busy()
busy() –– itit isis no
no longer
longer necessary
necessary toto illustrate
illustrate that
that
Note that
itit takes I have removed the method busy() – it is no longer necessary to illustrate that
takes time
time toto read
read thethe zip
zip codes.
codes. The
The class
class overrides
overrides also also the
the method
method done(),
done(), andand itit isis
itperformed
takes timebyto EDT read after
the zip codes. The class overrides also the method done(), and it is
performed by EDT after doInBackground()
doInBackground() isis executed.
executed. Note Note how how toto get
get the
the return
return value
value
performed by EDT after doInBackground() is executed. Note how to get the return value
with
withthethemethod
methodget(),get(),andandhow
howthethevalue
valueisisused
usedtotoupdate
updatethe thelist
listbox.
box.
with the method get(), and how the value is used to update the list box.
Finally,
Finally,there
thereisistotonote
notehow
howthe
theworker
workerthread
threadstarts
startsininthe
theevent
eventhandler:
handler:
Finally, there is to note how the worker thread starts in the event handler:
new Zipcodes(chooser.getSelectedFile()).execute();
new Zipcodes(chooser.getSelectedFile()).execute();
new Zipcodes(chooser.getSelectedFile()).execute();

10.2 A TIMER
10.2
10.2 A ATIMER
TIMER
I have previously shown how to use a Timer, but Swing also defines a Timer class that in
I have
I the
have previously
previously shown how to
useuse a Timer, butbut Swing also defines a Timer class thatin in
same mannershown how
as previously to performs
a Timer, Swing
a particular also
method defines a Timer
at certain times, class that
but the main
thethe same
same manner
manner as as previously
previously performs
performs a particular
a particular method
method at at certain
certain times,
times, butbut
thethe main
main
difference
difference and
and its justification is that it is performed in EDT. It works as, after an initial
difference and itsits justification
justification is is that
that it it
is is performed
performed in in EDT.
EDT. It It works
works as,as, after
after anan initial
initial
period
period it at a certain time interval fires an ActionEvent, which registered listeners can catch.
period it it
at at a certain
a certain time
time interval
interval fires
fires anan ActionEvent,
ActionEvent, which
which registered
registered listeners
listeners cancan catch.
catch.

119
119
119 119
JAVA 8:MULTITHREADED PROGRAMS Swing

The program Thread33 opens a window as shown below, where there are two buttons.
Between the two buttons is a JLabel, which from the start is blank. If you click on the
Start button, the program starts a timer that ticks every second where a counter variable is
increased by 1 and the value is shown in the label component. If you click the Stop button
the timer stops, and you can start it again by clicking Start.

Brain power By 2020, wind could provide one-tenth of our planet’s


electricity needs. Already today, SKF’s innovative know-
how is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

120
JAVA 8:MULTITHREADED PROGRAMS swIng
JAVA 8:MULTITHREADED PROGRAMS Swing

The code is the following:


The code is the following:
package thread33;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class MainView extends JFrame


{
private DefaultListModel model = new DefaultListModel();
private JButton cmd1 = new JButton("Start");
private JButton cmd2 = new JButton("Stop");
private JLabel lbl = new JLabel();
private Timer timer = null;
private int counter = 0;

public MainView()
{
super("Thread33");
setSize(300, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createView();
setVisible(true);
}

private void createView()


{
JPanel top = new JPanel(new BorderLayout(20, 0));
cmd1.addActionListener(this::start);
cmd2.addActionListener(this::stop);
cmd2.setEnabled(false);
top.add(cmd1, BorderLayout.WEST);
top.add(cmd2, BorderLayout.EAST);
top.add(lbl);
JPanel panel = new JPanel(new BorderLayout(0, 20));
panel.setBorder(new EmptyBorder(20, 20, 20, 20));
panel.add(top, BorderLayout.NORTH);
add(panel);
timer = new Timer(1000, this::tick);
lbl.setHorizontalAlignment(JLabel.CENTER);
}

121
121
JAVA 8:MULTITHREADED PROGRAMS Swing
JAVA 8:MULTITHREADED PROGRAMS swIng

public void tick(ActionEvent e)


{
lbl.setText("" + (++counter));
}

public void start(ActionEvent e)


{
timer.start();
cmd1.setEnabled(false);
cmd2.setEnabled(true);
}

public void stop(ActionEvent e)


{
timer.stop();
cmd1.setEnabled(true);
cmd2.setEnabled(false);
}
}

There
Thereisisnot
notmuch
muchtotoexplain,
explain,but
butyou
youshould
shouldnote
notehow
howtotocreate
createa atimer
timerand
andassigns
assignsan
an
event handler.
event handler.

122
122
JAVA 8:MULTITHREADED PROGRAMS Calendar

11 CALENDAR
As a final example, I will show the development of a program that can display a calendar
on the screen, but in addition, the program should keep track of appointments and the like.
There are many such programs for any platform, and the goal of the following is primarily
to write a program that uses multiple threads. When you study the finished program code
or test the program should also notice that the application uses more details on Swing, not
mentioned in the previous books.

11.1 TASK FORMULATION


The task is to write a program that in a window can display a calendar. The window should
show the calendar for a month and it should be possible to navigate in the calendar, for
example next month, next year and so on. It should also be possible to enter a specific
year and a month and then go directly to that month. The program shall cover the period
from year 0 to year 9999, and the program must take account of the shift from the Julian
calendar to the Gregorian calendar. The program should also be able to save a calendar for
a selected period to a text file.

The program should be used as a daily calendar program, and one should therefore also
be able to enter notes and appointments, set alarms and set special (custom) anniversaries
beyond the days that the calendar was born with (holidays). The calendar must give a
warning, when the time for an appointments occurs.

Remark
The result of this first phase is a project library, as preliminary only have a subdirectory
with this task formulation.

11.2 ANALYSIS
The analysis will consist of

1. a requirement specification
2. a prototype for the user interface

123
JAVA 8:MULTITHREADED PROGRAMS Calendar

11.2.1 REQUIREMENT SPECIFICATION

The main application window should primarily show a calendar for a specific month.

The calendar will cover the period from year 0 to year 9999 and should take account of
the shift from the Julian to the Gregorian calendar. It is decided that the switch from the
Julian to the Gregorian calendar is set to 1582, and then the 4 October is followed by the
15 October.

For each date, the calendar must display the following information:

-- the day’s number in the month


-- the week day’s name
-- the week’s number in the year, if it is a monday
-- an indication if it is a public holiday or anniversary
-- a mark when created notes
-- a mark when created appointments
-- a mark when created anniversaries

For the holidays, the program must be pre-programmed to (know) the following days:

-- New Year’s Day


-- Palm Sunday
-- Maundy Thursday
-- Good Friday
-- Easter Sunday
-- Easter Monday
-- Prayer Day
-- Christ’s Ascension
-- Pentecost
-- Whit Monday
-- Christmas Eve
-- Christmas Day
-- Second Christmas Day

and also the program must be able to show custom anniversaries (for example the wife’s
birthday). An anniversary falls on a specific date and every year after 1582 (with the option
to specify a start and end year). If an anniversary specifies d. 29/2, and it is not a leap year
the date 1/3 should be used.

124
JAVA 8:MULTITHREADED PROGRAMS Calendar
JAVA 8:MULTITHREADED PROGRAMS Calendar

The program distinguishes between notes and appointments. A note is any text entered for
The program distinguishes between notes and appointments. A note is any text entered for
a specific date, and there can be more notes for the same date. An appointment is a short
a specific date, and there can be more notes for the same date. An appointment is a short
message relating to a specific time (clock) and the program must be able to automatically
message relating to a specific time (clock) and the program must be able to automatically
notifies the user when the time for an appointment occurs. Notes will be saved until the
notifies the user when the time for an appointment occurs. Notes will be saved until the
user manult delete them. Appointments should be automatically deleted when the time is
user manult delete them. Appointments should be automatically deleted when the time is
exceeded, but maybe there should be an option that an appointment should be stored after
exceeded, but maybe there should be an option that an appointment should be stored after
the time is exceeded.
the time is exceeded.
Regarding appointments it must be able to make an appointment for a specific date and for
Regarding appointments it must be able to make an appointment for a specific date and for
a specific time. There may then be several appointments the same day, and an appointment
a specific time. There may then be several appointments the same day, and an appointment
is in principle only plain text. An appointment can span multiple days. An appointment
is in principle only plain text. An appointment can span multiple days. An appointment
can also have a start time, an end time, or both, and if so, the program should come with
can also have a start time, an end time, or both, and if so, the program should come with
a warning if the timing conflicts. When the time of an appointment occurs, the program
a warning if the timing conflicts. When the time of an appointment occurs, the program
must come with a warning that must appear in the user interface. It is adopted
must come with a warning that must appear in the user interface. It is adopted
1. the warning should appear at the day’s start (when the computer is turned on)
1. the warning should appear at the day’s start (when the computer is turned on)
2. 1 hour before the appointment occurs
2. 1 hour before the appointment occurs
3. 15 minutes before the appointment occurs
3. 15 minutes before the appointment occurs
4. 5 minutes before the appointment occurs
4. 5 minutes before the appointment occurs
5. when the appointment occurs, and the appointment should be deleted
5. when the appointment occurs, and the appointment should be deleted
Functions:
Functions:
Navigate the calendar:
Navigate the calendar:
-- Shift to previous year
- Shift to previous year
-- Shift to previous month
- Shift to previous month
-- Shift to next month
- Shift to next month
-- Shift to next year
- Shift to next year
-- Enter year and month and the calendar must shift to that month
- Enter year and month and the calendar must shift to that month
The program must be able to save a calendar as a comma delimited text file with the
The program must be able to save a calendar as a comma delimited text file with the
following format:
following format:

year; month number; month name; day in month; day name; week number [; holiday]

and an example could be


and an example could be
2012;4;April;1;Sunday;14;Palm Sunday
2012;4;April;2;Monday;14;
2012;4;April;3;Tuesday;14;

125
125
JAVA 8:MULTITHREADED PROGRAMS Calendar

The program must also have the following features:

-- Maintenance of anniversaries
-- Maintenance of notes
-- Maintenance of appointments
-- Watch
-- Alarm (that comes with a warning a certain time)
-- Timer (that comes with a warning when a timer reach 0)
-- Stopwatch

11.2.2 THE PROTOTYPE

The prototype is a NetBeans project called Calendar. The result is a program that only
opens the window below. All the program’s functions are placed in a toolbar at the top of
the window. At the bottom is a status bar showing

-- the current month


-- the current day (today)
-- an icon that shows whether there is set an alarm (if not, no icon appears)
-- an icon that shows whether there is set a timer (if not, no icon appears)

126
JAVA 8:MULTITHREADED PROGRAMS Calendar

For each date is shown the day’s number in the month (and later the week number), and
the color indicates whether it is a public holiday. In addition, there are three icons, which
means that there are

1. notes for that date


2. appointments for that date
3. anniversaries of that date

If you click on an icon, you get a simple dialog box with information, and for appointments
it should also be possible to cancel the appointment.

If you right click on a specific date you get a menu where you can

1. create a note
2. create an appointment
3. create an anniversary

As for the icons in the toolbar, the following applies:

1. The first four icons (arrows) are used to navigate the calendar.
2. The next opens a dialog box so you can navigate to a specific month.
3. The sixth icon opens a dialog to maintenance notes.

127
JAVA 8:MULTITHREADED PROGRAMS Calendar

4. The seventh icon opens a dialog to maintenance appointments.


5. The next shows the clock (how the clock should look like is not yet determined).
6. The next again is for the stopwatch. Opens a dialog box to start or stop the stopwatch.
7. The tenth icon opens a dialog box to maintenance of alarms.
8. The eleventh icon opens a dialog box to maintaining timers.
9. The next icon is to export of a calendar to a textfile and opens a dialog box for
selecting the period.
10. The second last icon opens a dialog box to maintenance of anniversaries.
11. The last icon is the settings for the program, but it has not yet determined which
settings should be talking about, but possibly colors.

11.3 DESIGN
The design phase are performed in five steps:

1. Design of the architecture


2. Design of the model layer
3. Design of the DAL layer
4. Design of the user interface
5. Design of the controller layer

The design starts to create a copy of NetBeans project from the analysis (the prototype).
The copy is called Calendar1.

11.3.1 DESIGN OF THE ARCHITECTURE

The program’s architecture has a classic MVC architecture:

The emphasis of the project is the model layer that has relatively complex algorithms.

128
JAVA
JAVA8:MULTITHREADED
8:MULTITHREADEDPROGRAMS
PROGRAMS Calendar
Calendar

11.3.2 DESIGN OF
11.3.2 DESIGN OFTHE
THEMODEL
MODELLAYER
LAYER
Java
Java has
has classes
classes that
that represent
represent aa date,
date, but
but since
since itit isis aa requirement
requirement that
that the
the calendar
calendar must
must
support
support the
the change
change from
from the
the Julian
Julian calendar
calendar toto thethe Gregorian
Gregorian calendar,
calendar, itit isis decided
decided to
to
implement a custom date type. The class must represent a date as
implement a custom date type. The class must represent a date as an int in the format an int in the format
YYYYMMDD:
YYYYMMDD:

The
The class
class must
must have
have aa number
number of of methods,
methods, and
and the
the following
following design
design shows
shows only
only the
the most
most
important,
important, but
but there
there will
will be
be many
many more:
more:

package calendar.models;

/**
* Represents a date between year 0 and year 9999. The class takes into
* account the shift from the Julian to the Gregorian calendar.
*/

Challenge the way we run

EXPERIENCE THE POWER OF


FULL ENGAGEMENT…

RUN FASTER.
RUN LONGER.. READ MORE & PRE-ORDER TODAY
RUN EASIER… WWW.GAITEYE.COM

1349906_A6_4+0.indd 1 22-08-2014 12:56:57

129
129
JAVA8:MULTITHREADED
JAVA 8:MULTITHREADEDPROGRAMS
PROGRAMS Calendar
Calendar

public class Date implements Comparable<Date>


{
private int value; // represents a date as YYYYMMDD

/**
* Returns the days number int the week :
* 1 = monday
* 2 = tuesday
* 3 = wednesday
* 4 = thursday
* 5 = friday
* 6 = saturday
* 7 = sunday
* @return The days number int the week
*/
public int getWeekDay()
{
throw new UnsupportedOperationException();
}

/**
* Moves the current date, a day ahead.
*/
public void nextDay()
{
throw new UnsupportedOperationException();
}

/**
* Moves the current date back a day.
*/
public void prevDay()
{
throw new UnsupportedOperationException();
}

/**
* Moves the current date, a month ahead.
*/
public void nextMonth()
{
throw new UnsupportedOperationException();
}

/**
* Moves the current date back a month.
*/

130
130
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS Calendar
Calendar

public void prevMonth()


{
throw new UnsupportedOperationException();
}

/**
* Moves the current date, a year ahead.
*/
public void nextYear()
{
throw new UnsupportedOperationException();
}

/**
* Moves the current date back a year.
*/
public void prevYear()
{
throw new UnsupportedOperationException();
}

/**
* Calculate the number of the week in the year, where week number 1
* is the first week in the year that contains a thursday.
* @return the number of the week in the year
*/
public int getWeekNumber()
{
throw new UnsupportedOperationException();
}

/**
* If this date is a holiday the method returns the name, and else the
* method returns null.
* The method can return the following names:
* New Year's Day
* Palm Sunday
* Maundy Thursday
* Good Friday
* Easter Sunday
* Easter Monday
* Prayer Day
* Christ's Ascension
* Pentecost
* Whit Monday
* Christmas Eve

131
131
JAVA 8:MULTITHREADED PROGRAMS Calendar
JAVA 8:MULTITHREADED PROGRAMS Calendar

* Christmas Day
* Second Christmas Day
* @return the name of a holiday or null
*/
public String getHoliday()
{
throw new UnsupportedOperationException();
}

public int compareTo(Date date)


{
throw new UnsupportedOperationException();
}
}

The method getWeekDay() is complex because it must return the correct day for the entire
The method getWeekDay() is complex because it must return the correct day for the entire
range of dates, that the calendar span. The approach is to implement an algorithm that
range of dates, that the calendar span. The approach is to implement an algorithm that
determines the number of days from d. 1/1 year 0 and up to a given date. If you determines
determines the number of days from d. 1/1 year 0 and up to a given date. If you determines
the week day for a known date, then the day of the week can be calculated.
the week day for a known date, then the day of the week can be calculated.

This e-book
is made with SETASIGN
SetaPDF

PDF components for PHP developers

www.setasign.com

132
132
JAVA 8:MULTITHREADED PROGRAMS Calendar
JAVA 8:MULTITHREADED PROGRAMS Calendar

The calculation methods for moving the calendar one day, month or year forward or backward
The calculation methods for moving the calendar one day, month or year forward or backward
are also all relatively complex because they must take into account leap years and the shift
are also all relatively complex because they must take into account leap years and the shift
between the Julian and Gregorian calendar.
between the Julian and Gregorian calendar.

The method getWeekNumber() is implemented using a method which determines the number
The method getWeekNumber() is implemented using a method which determines the number
of days from the beginning of the year to the current date.
of days from the beginning of the year to the current date.

Finally, there is the method getHoliday() which is a complex algorithm. Some of the public
Finally, there is the method getHoliday() which is a complex algorithm. Some of the public
holidays fall on fixed dates and are unproblematic, while the other can be determined from
holidays fall on fixed dates and are unproblematic, while the other can be determined from
the date of Easter Sunday. There are algorithms that can determine Easter Sunday, and
the date of Easter Sunday. There are algorithms that can determine Easter Sunday, and
the method can therefore be implemented by implement such an algorithm. I will use an
the method can therefore be implemented by implement such an algorithm. I will use an
algorithm called Gaus’s algorithm.
algorithm called Gaus’s algorithm.

Based in the class Date, the program’s data model is outlined as follows:
Based in the class Date, the program’s data model is outlined as follows:

The other classes in the data model are defined as follows:


The other classes in the data model are defined as follows:
package calendar.models;

/**
* Represents a time.
*/

133
133
JAVA 8:MULTITHREADED PROGRAMS Calendar
JAVA 8:MULTITHREADED PROGRAMS Calendar

public class Time implements Comparable<Time>


{
private int value; // represents a time as HHMMSS

public int compareTo(Time time)


{
throw new UnsupportedOperationException();
}
}

package calendar.models;

public class Appointment


{
private int id; // indentifier for this Appointment
private Date date1; // start date for this Appointment
private Time time1; // start time for this Appointment
private Date date2; // end date for this Appointment (may be null)
private Time time2; // end time for this Appointment (may be null)
private String text; // the text for this Appointment
private boolean save; // where this Appointment shoul be deleted (false)
}

package calendar.models;

public class Note


{
private int id; // indentifier for this Note
private Date date; // the date for this Note
private String title; // the title of this Note
private String text; // the text for this Note
}

package calendar.models;

public class Anniversary


{
private int id; // indentifier for this Anniversary
private int month; // month for this Anniversary
private int day; // day for this Anniversary
private int year1 = 1583; // start year for this Anniversary
private int year2; // end year for this Anniversary (may be null)
private String name; // name for this Appointment
}

package calendar.models;

import java.util.*;

134
134
JAVA 8:MULTITHREADED PROGRAMS Calendar
JAVA 8:MULTITHREADED PROGRAMS Calendar

/**
* Represents information for a date in the calenndar.
*/
public class MainDate
{
private Date date;
private List<Anniversary> anniversaries = new ArrayList();
private List<Appointment> appointments = new ArrayList();
private List<Note> notes = new ArrayList();
}

package calendar.models;

/**
* Represents a calendar for a month.
*/
public class MainModel
{
private Date date; // the current date
private MainDate[][] table = new MainDate[6][7];
}

Free eBook on
Learning & Development
By the Chief Learning Officer of McKinsey

Download Now

135

135
JAVA 8:MULTITHREADED PROGRAMS Calendar
JAVA 8:MULTITHREADED PROGRAMS Calendar

11.3.3 DESIGN OF THE DAL LAYER


11.3.3 DESIGN OF THE DAL LAYER
Data for notes, appointments and anniversaries should be saved persistent, and it is decided
Data for notes, appointments and anniversaries should be saved persistent, and it is decided
to do that by object serialization. Since the program is intended as a personal tool it can
to do that by object serialization. Since the program is intended as a personal tool it can
be cumbersome to install the program, if you first must create a database that the program
be cumbersome to install the program, if you first must create a database that the program
has to connect to. If there are relatively few notes and appointments, it is also unnecessary
has to connect to. If there are relatively few notes and appointments, it is also unnecessary
to use a database and it is simpler to serialize the data to a file.
to use a database and it is simpler to serialize the data to a file.

The basis is the following interface, and the methods names should explain what they are
The basis is the following interface, and the methods names should explain what they are
used for:
used for:
package calendar.dal;

import java.util.List;

import calendar.models.*;

public interface Repository


{
public List<Note> getNotes();
public List<Note> getNotes(Date date);
public List<Note> getNotes(Date from, Date to);
public boolean addNote(Note note);
public boolean updateNote(Note note);
public boolean deleteNote(int id);
public boolean deleteNotes(Date date);
public boolean deleteNotes(Date from, Date to);
public List<Anniversary> getAnniversaries();
public List<Anniversary> getAnniversaries(Date date);
public boolean addAnniversary(Anniversary anniversary);
public boolean updateAnniversary(Anniversary anniversary);
public boolean deleteAnniversary(int id);
public boolean deleteAnniversaries(Date date);
public boolean deleteAnniversaries(Date from, Date to);
public List<Appointment> getAppointments();
public List<Appointment> getAppointments(Date date);
public List<Appointment> getAppointments(Date from, Date to);
public boolean addAppointment(Appointment appointment);
public boolean updateAppointment(Appointment appointment);
public boolean deleteAppointment(int id);
public boolean deleteAppointments(Date date);
public boolean deleteAppointments(Date from, Date to);
}

The program must then instantiate a concrete repository class, what I will call IORepository.
The program must then instantiate a concrete repository class, what I will call IORepository.

136
136
JAVA 8:MULTITHREADED PROGRAMS Calendar

11.3.4 DESIGN OF THE USER INTERFACE

The main window is defined by the prototype. In addition, the user interface includes a
series of dialog boxes corresponding to the functions of the program, as defined in the
analysis. The following diagram shows an overview.

If, for example looking at NotesView it is a dialog box that shows a list of all notes within a
selected period. NoteView is an associated dialog box that is used to maintain a single note.

In addition to the dialog boxes, as shown in the diagram, there will also be a dialog box
for maintenance settings. It is still not decided which settings it should be, but the choice
to select where to store data, will be one of them.

11.3.5 DESIGN OF THE CONTROL LAYER

Control layer will be thin, and there will be only controller classes the most complex dialog
boxes, and for the most part, these are as simple dialog boxes. However, all that is necessary
to trigger warnings for appointments and alarms, and thus everything concerning threads
are implemented in the controller layer.

137
JAVA 8:MULTITHREADED PROGRAMS Calendar

11.4 PROGRAMMERING
The programming is carried out in the following steps (iterations):

1. Navigate the calendar and including the implementation of the class Date
2. Implentation maintenance of notes and of IORepository
3. Implementation of appointments and anniversaries
4. Implementation of all functions relating to the clock and including alarm and timer
5. Implementation of export of a calendar
6. A last iteration and code review

11.4.1 ITERATION 1

The iteration starts with creating a copy of the NetBeans project from the design. The copy
is called Calendar2.

As the first I have implemented the class Date. It is the program’s most important and certainly
most comprehensive class. Many of the algorithms are complex, and are documented in the
code. In addition to the class Date the model layer is extended with a class CalenderException.

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

138
JAVA 8:MULTITHREADED PROGRAMS Calendar

Main class MainDate is extended with a constructor, which has as a parameter that is a
Date object, and the class has a corresponding get method.

The class MainModel is implemented so that it represents 42 dates, which is the number
of dates needed to represent a whole month with 6 rows by 7 columns.

There is created a dialog box where you can select a month and enter a year. Since it is a
very simple dialog box there is no controller, but to the package calendar.views are added
three classes:

1. GotoEvent which defines an event for selecting a month


2. GotoListener defining a single event handler for an event of the type GotoEvent
3. GotoView as the dialog box

The class MainView from the prototype is modified, which primarily consist of attaching
event handlers for the first five buttons in the toolbar.

Then the first iteration in principle is finished, so you can navigate the calendar, but it is
important that the result be thoroughly tested, and it will specifically say the class Date.
The best way to test the result is by using and navigating the calendar:

1. Open the program and validate that the current month is displayed correctly:
-- the right dates
-- the right week days
-- the right week numbers
-- the right selections for Sundays and holidays
2. Navigate a month forward and test similar the result. Repeat it a month at a time
for five years.
3. Navigate five years back, or until you reaches the current month. Test the result
for each month.
4. Navigate one month back and check the corresponding result. Repeat it a month
at a time for five years.
5. Navigate five years forward, or until you have the current month. Check for each
year the result.
6. Select the date 1/1 1582 and navigate the calendar forward one month at a time
until 1/1 1583. Check that October is correct.
7. Navigate the calendar back a month at a time until 1/1 in 1582 and controls of
October is correct.
8. Select the date 1/2 1500 and check that there are 29 days in February.

139
JAVA 8:MULTITHREADED PROGRAMS Calendar
JAVA 8:MULTITHREADED
JAVA 8:MULTITHREADED PROGRAMS
PROGRAMS Calendar
Calendar

9. Select the date 1/2 1700 and check that there are 28 days in February.
9. Select
9. Select the
the date
date 1/2
1/2 1700
1700 and
and check
check that
that there
there are
are 28
28 days
days in
in February.
February.
10. Navigate four years back and make sure that there are 29 days in February.
10. Navigate
10. Navigate four
four years
years back
back and
and make
make sure
sure that
that there
there are
are 29
29 days
days in
in February.
February.
11. Navigate eight years forward and check that there are 29 days in February.
11. Navigate
11. Navigate eight
eight years
years forward
forward and
and check
check that
that there
there are
are 29
29 days
days in
in February.
February.
12. Use the Internet to determine the date of Easter Day for the next 10 years from
12. Use
12. Use the
the Internet
Internet toto determine
determine thethe date
date of
of Easter
Easter Day
Day forfor the
the next
next 10
10 years
years from
from
the current year. Check that the program shows the same dates for Easter Day.
the current
the current year.
year. Check
Check that
that the
the program
program shows
shows the
the same
same dates
dates for
for Easter
Easter Day.
Day.
13. Select the date 1/12 9999. Navigate five months back. Navigate the calendar forward
13. Select
13. Select the
the date
date 1/12
1/12 9999.
9999. Navigate
Navigate five
five months
months back.
back. Navigate
Navigate the
the calendar
calendar forward
forward
as far as possible.
as far
as far as
as possible.
possible.
14. Select the date 1/1 0. Navigate five months ahead. Navigate the calendar as far
14. Select
14. Select the
the date
date 1/1
1/1 0.
0. Navigate
Navigate five
five months
months ahead.
ahead. Navigate
Navigate the
the calendar
calendar as
as far
far
back as possible.
back as
back as possible.
possible.

11.4.2 ITERATION 2
11.4.2 ITERATION
11.4.2 ITERATION 22
The iteration starts with creating a copy of the NetBeans project from the iteration 1. The
The iteration
The iteration starts
starts with
with creating
creating aa copy
copy of
of the
the NetBeans
NetBeans project
project from
from the
the iteration
iteration 1.
1. The
The
copy is called Calendar3.
copy isis called
copy called Calendar3.
Calendar3.

I start to implement the class IORepository. First I moved the interface Repository to the
II start
start to
to implement
implement the
the class
class IORepository.
IORepository. First
First II moved
moved thethe interface
interface Repository
Repository to
to the
the
package calendar.models and thus it defines which services the DAL layer provides. The
package calendar.models
package calendar.models and
and thus
thus itit defines
defines which
which services
services the
the DAL
DAL layer
layer provides.
provides. The
The
interface has been extended with a single method:
interface has
interface has been
been extended
extended with
with aa single
single method:
method:
getNote(int id)
getNote(int id)

which returns a note with a specific id. That must be defined corresponding methods
which returns
which returns aa note
note with
with aa specific
specific id.
id. That
That must
must bebe defined
defined corresponding
corresponding methods
methods
respectively for anniversaries and appointments, but I will first do that in the next iteration.
respectively for
respectively for anniversaries
anniversaries and
and appointments,
appointments, butbut II will
will first
first do
do that
that in
in the
the next
next iteration.
iteration.

Next, the class IORepository is implemented as follows:


Next, the
Next, the class
class IORepository
IORepository isis implemented
implemented as
as follows:
follows:
public class IORepository implements Repository, Serializable
public class IORepository implements Repository, Serializable
{
{private static final String filename = "calendar.dat";
private
private static final String filename = "calendar.dat";
List<Anniversary> anniversaries;
private List<Appointment>
List<Anniversary> appointments;
anniversaries;
private
private List<Note> notes; appointments;
private List<Appointment>
private int
private List<Note> notes;
lastAnniversary = 0;
private int lastAnniversary
private int lastAppointment = = 0;
0;
private int
private int lastNote
lastAppointment
= 0; = 0;
private int lastNote = 0;

public IORepository()
{
public IORepository()
{deSerialize();
} deSerialize();
}

140
140
140
JAVA
JAVA 8:MULTITHREADED
8:MULTITHREADED PROGRAMS
PROGRAMS Calendar
Calendar

So
So far,
far, itit isis decided
decided that
that the
the program’s
program’s data
data should
should bebe serialized
serialized in
in aa file
file in
in the
the user’s
user’s home
home
directory.
directory. The class must implement the interface Repository, and to facilitates the work you
The class must implement the interface Repository, and to facilitates the work you
can
cantake
takeadvantage
advantageof ofthat
thatNetBeans
NetBeanscan canautomatically
automaticallygenerate
generateaastub
stubforforall
allmethods
methodsdefined
defined
in
inthe
theinterface.
interface.IfIfyou youright-click
right-clickon onthe
theclass
classname
nameandandhere
herechoose
chooseInsert
InsertCodeCodeyou
youprovides
provides
an
an opportunity
opportunity to to choose
choose Implement
Implement Method…
Method… and and then
then NetBeans
NetBeans automatically
automatically create
create aa
stub
stub for
for allall methods
methods defined
defined inin the
the interface
interface (if
(if you
you choose
choose them
them all),
all), and
and an an example
example isis ::

@Override
public List<Anniversary> getAnniversaries() {
throw new UnsupportedOperationException("Not supported yet.");
}

The methods
The methods must
must then
then be
be implemented,
implemented, and
and in
in this
this iteration,
iteration, II have
have only
only implemented
implemented
the methods
the methods related
related notes.
notes.

360°
thinking .

360°
thinking . 360°
thinking .
Discover the truth at www.deloitte.ca/careers Dis

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers © Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers


141
141
JAVA 8:MULTITHREADED PROGRAMS Calendar
JAVA 8:MULTITHREADED PROGRAMS Calendar

As
As aa next
next step,
step, II have
have defined
defined the
the three
three model
model classes
classes Anniversary,
Anniversary, Appointment
Appointment and and Note
Note
(the first two should only be used in the next iteration). All three classes must
(the first two should only be used in the next iteration). All three classes must be defined be defined
serializable,
serializable, and
and when
when the
the individual
individual objects
objects also
also should
should bebe sorted,
sorted, they
they must
must bebe defined
defined
comparable.
comparable. It is quite simple to implement the three classes, as they mainly consist of
It is quite simple to implement the three classes, as they mainly consist of get
get
and set methods and an override of equals() and compareTo(), but here you can
and set methods and an override of equals() and compareTo(), but here you can facilitate the facilitate the
work
work byby the
the same
same manner
manner asas described
described above
above to
to let
let NetBeans
NetBeans create
create stubs
stubs for
for each
each method.
method.

II add
add aa class
class DataAdapter
DataAdapter that
that isis used
used to
to instantiate
instantiate an
an object
object of
of the
the type
type Repository.
Repository. The
The
class is written as a singleton:
class is written as a singleton:

package calendar.models;

import calendar.dal.*;

public class DataAdapter


{
private static DataAdapter instance = null;

private Repository data;

private DataAdapter()
{
data = new IORepository();
}

public static DataAdapter getInstance()


{
if (instance == null)
{
synchronized (DataAdapter.class)
{
if (instance == null) instance = new DataAdapter();
}
}
return instance;
}

public Repository getData()


{
return data;
}
}

142
142
JAVA 8:MULTITHREADED PROGRAMS Calendar

With these classes in place, I can write the code for maintenance of notes. First there is
changes in the class MainView, so it opens a popup menu if you right-click on a day in
the calendar. The menu has three options:

1. Create note
2. Create appointment
3. Create anniversary

A popup menu has the type JPopupMenu and the definition of the menu is simple and is
done by a call of a method in the class’s constructor. For each of the panels that define a day
in the calendar is assigned an event handler for the mouse, and the popup menu opens if
you right-click a day in the calendar. To maintain notes, I have added the following classes:

-- NoteController, which is controller for a dialog box for maintenance of a note.


-- NoteEvent defining an event that the above controller can fire if adding a note, if
a note is changed or if a note is deleted.
-- NoteListener defining a listener for events of type NoteEvent.
-- NoteView as the dialog box for the controller NoteController and is used both to
create a note and to edit a note.
-- Filter that defines a filter for a JTable.
-- FilterListener that defines a listener to a filter.
-- NotesTable, which defines a data model to a JTable.
-- DateRenderer defining a CellRenderer to a JTable.
-- NotesView which opens a dialog box with a JTable that shows an overview of all notes.

Finally is added a class GUI with helper methods for design of the graphical user interface.

If you right-click a day in the calendar and in the popup menu, select Create note, you get
a window as shown below (the dialog box NoteView):

143
JAVA 8:MULTITHREADED PROGRAMS Calendar

We will turn your CV into


an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

144
JAVA 8:MULTITHREADED PROGRAMS Calendar

If you click on the icon for notes in the toolbar, you get the following window (dialog box
NotesView):

If you double-click on the line for the note, the same dialog as above opens, and you can
edit the note and possible. delete it.

The result of the iteration has been tested as follows:

1. Open the program.


2. Right-click on a day the current month. Select Create note and create a new note.
3. Navigate the calendar 5 months forward.
4. Right-click on a day the current month. Select Create note and create a new note.
5. Navigate the calendar 2 months back.
6. Right-click onn a day the current month. Select Create note and create a new note.
7. Navigate the calendar 3 months back.
8. Right-click on the same day as for the first note. Select Create note and create a
new note.
9. Close the program.
10. Open the program again.

145
JAVA 8:MULTITHREADED PROGRAMS Calendar

11. Select Maintenance of notes in the and test where all notes are shown and in the
right order.
12. Double-click on one of the notes and change the text.
13. Double-click on the same note and change the title. Check that the JTable is updated.
14. Close the program.
15. Open the program again.
16. Select Maintenance of notes.
17. Test the filter.
18. Double-click at the same note as before annd check the changes are preserved.
19. Delete the note.
20. Close the program.
21. Open the program again.
22. Select Maintenance of notes.
23. Check that the note is deleted.

11.4.3 ITERATION 3

As before the iteration starts with creating a copy of the NetBeans project from the previous
iteration. The copy is called Calendar4.

In this iteration, the task is to implement the two functions maintenance of appointments
and maintenance of anniversaries. In addition, the iteration include that the calendar should
displays icons for the days when registered appointments, anniversaries and also notes.
Implementing maintenance of appointments is the most comprehensive, so I will start there.

Before that, I have to adjust the model:

-- The class Time is implemented, but there has been a change so that a time alone
consists of hours and minutes. In this case, the class is used to record times on
appintments, and here it makes no sense to register seconds.
-- The two classes Appointment and Anniversary must implement the interface Comparable,
such that objects can be sorted.
-- The interface Repository is expanded with two new methods that return either an
Appointment and an Anniversary for a given id.
-- The class IORepository is updated. First, the two new methods are implemented, and
also the code to all other method stubs are written. The code fills, but is basically
identical to the corresponding code for notes.

146
JAVA 8:MULTITHREADED PROGRAMS Calendar

If you right-click a day in the calendar and in the popup menu chooses Create appointment,
you get the following dialog box:

On the left side you can enter an appointment for the current day. On the right side is a
JTable showing an overview of appointments for the same day. Here you can edit the individual
cells. The purpose is that you can correct times if there are appointments that conflicts.

147
JAVA 8:MULTITHREADED PROGRAMS Calendar

If you in the toolbar chooses Maintains of appointments you get the following window:

which shows an overview of the appointments that are created. Basically it is a JTable with
a filter. If you double click on a line opens the same dialog as above, so you can modify
the appointment and alose delete it.

For the first dialog box is added the following classes and interfaces:

-- AppointmentEvent defining an event object which is fired when creating a new


appointment, when an appointment is changed and when an appointment is deleted.
-- AppointmentListener which is an interface, which defines the listeners for the events
of the type AppointmentEvent.
-- AppointmentController as a controller for the dialog box. It is a relatively extensive
class since it must validate where there are conflicting appointments. If you try to
save an appointment that conflicts, you get a warning. Two appointments conflicts
if they defines overlapping time intervals.
-- AppointmentTable as a data model for the JTable that dialog box contains. The data
model must support editing of cells.

148
JAVA 8:MULTITHREADED PROGRAMS Calendar

-- TimeCellEditor, which defines a CellEditor to edit a time.


-- DateCellEditor, which defines a CellEditor to edit a date.
-- TimeRenderer, which defines a CellRenderer for a column of the type Time.
-- AppointmentView which is the dialog box.

For the second dialog box is added the following classes:

-- AppointmentsTable that is a data model for dialog’s JTable.


-- AppointmentsView, that is the dialog box.

To test the function I have deleted everything that is created by manually delete the file
calendar.dat. Next, I have completed the following test:

1. Created an appointment for the 8th in the current month from 10:00 to 11:00.
2. Created an appointment for the same day that starts at 12:00 (no end).
3. Created an appointment for the same day from 8:30 to 9:30.
4. Created an appointment for the same day, but without time indication. It results
in a conflict, and I have agreed to create the appointment anyway.
5. Closed the program.
6. Open the program again.
7. Open maintenance appointments from the toolbar.
8. Checked that the appointments are sorted correctly.
9. Double-click on the second of the above appointments (that without end time)
and entered 14:00 as the end time. When you save you gets a warning about
conflicting appointments when the appointment conflicts with the appointment
without time indication.
10. Double-click on the appointment without indication of time and set the time
interval from 15:00 to 16:00. When saving, there will be no warining – there is
no longer conflicting appointments.
11. Created an appointment starting d. 8th and start at 17:00 and ends the next day
at 9:00.
12. Opened the list of appointments. Double-click on above appointment and deleted it.
13. Close the program.
14. Open the program again and opened the list with appointments and found that
everything looks correct.
15. Created an appointment the 15th, the 22th and the 29th in the same month – all
without time indications.

149
JAVA 8:MULTITHREADED PROGRAMS Calendar

16. Edited the appointment for the 15th with a start and a end time, where the last
one should be smaller than the first. It should give an error. Fixed the end time,
so it is larger than the start time and saved the appointment.
17. Edited same appointment again and changed the end date to the day before. It
should give an error. The click Cancel to cancel the change.

Then there is maintenance of anniversaries. This feature is similar to the maintenance of


notes, and when then model classes are implemented, the function is implemented by added
the following types:

-- AnniversaryEvent that define an event, when added, modified or deleted an anniversary.


-- AnniverversaryListener defining listeners for events of the type AnniversaryEvent.
-- AnniversaryController which is controller class for the dialog box AnniversayView.
-- AnniversaryView which is the dialog box for maintenance of anniversaries.
-- AnniversariesTable defining a data model to a JTable with an overview of all
anniversaries.
-- IntegerRenderer, which is used to render cells of the type Integer.
-- AnniversariesView, there is the dialog box, which shows an overview of all anniversaries.

AXA Global
Graduate Program
Find out more and apply

150
JAVA 8:MULTITHREADED PROGRAMS Calendar

The function is tested by the same pattern as above, and I will not mention the individual
test cases here.

The calendar should similar to the prototype display icons for the days when created notes,
appointments or anniversaries. If you click on an icon, the application should open the
above dialog boxes, respectively for notes, appointments and anniversaries, but they should
only show an overview of the items (notes, appointments, anniversaries) for the current
day. Furthermore, it is decided that the calendar also must displays an icon for the days
that are holidays (the holidays that the class Date knows). If you here click on the icon,
you should get a simple popup that shows the holy day’s name:

In principle, it is easy to implement these changes, but there are changed in many places:

-- The interface Repository has been extended with three new methods used to test
whether a given day have respectively a note, an appointment or an anniversary.
-- The class IORepository is changed to implement the three new methods.
-- The class MainData is changed so that it no longer has collections of notes,
appointments and anniversaries. Indeed, one can consider completely remove the
class when it no longer adds much, but it is provisionally preserved for later changes.
-- The classes NoteView, AppointmentView and AnniversaryView are all updated as
the default constructor is changed to a constructor with two parameters which are
respectively a Date and a listener. The aim is that the calendar may be updated if
you click on one of the three icons for Note, Appointment or Anniversary.
-- The three classes NotesTable, AppointmentsTable and AnniversariesTable is changed
where added a default constructor and a constructor that from a Date creates a
model for that day.
-- The three classes NotesView, AppointmentsView and AnniversariesView is changed such
that the default constructor now has a listener as a parameter. Again, the reason
is that changes in the three collections may be reflected in the calendar (where an
icon if necessary must be removed).
-- Finally, the class MainView is updated to show the icons, and there are changes
for the event handling.

151
JAVA 8:MULTITHREADED PROGRAMS Calendar

I will not show the individual test cases here, but to test the latest addition and thus the
entire iteration you needs to create more notes, appointments and anniversaries spread over
several days and months thereafter to check that the right icons appear and act as they
should. In addition, you must test that the calendar is updated properly if you delete items.

11.4.4 ITERATION 4

The iteration starts with creating a copy of the NetBeans project from the previous iteration.
The copy is called Calendar5. In this iteration the following functions must be implemented
and tested:

1. Watch, that show a watch in the window.


2. Stopwatch, that implements a stopwatch.
3. Alarm, where the user can set an alarm that shows a waring after a given time.
4. Timer, where the user can enter a time, and the function shows a warning, when
the timer is 0.
5. Appointments, where en appointment for the current day must result in a warning,
when it’s time.

Watch
This is a simple function and should be an on/off function. If you clicks on the icon in
the toolbar, the function is turned on, and if you clicks again the function is turned off.

The calendar has a status bar, which shows the current date. It is agreed that the clock
should appear immediately afterwards, and the clock will tick every second. It’s simple to
add the necessary to the MainView. To control the clock is added a class MainController
that has a function that either starts or stops a timer and every time the timer is ticking,
is sent an event to the MainView (WatchEvent and WatchListener).

Stopwatch
Then there is the stopwatch. It has been decided that it should only be possible to start
one stopwatch. If you click on the button in the toolbar (and the stopwatch not already is
started), you get the following window:

152
JAVA 8:MULTITHREADED PROGRAMS Calendar

where you can start the stopwatch. If you do that, an icon appears in the lower right corner,
which indicates that the stopwatch is running and if you click this icon, opens the above
dialog boxes again, and you can see what the stopwatch displays and possible stop the clock.

To implement this feature, the model is extended by a class Stopwatch representing a stopwatch.
There is also added an event object StopEvent and an interface StopListener (both in the
model layer) as the class Stopwatch fire an event every time the clock has counted a second
forward. It means, when the clock starts it starts a timer that ticks every second. The event
is used to update the above dialog box, when the stopwatch ticks. The class ModelMain is
extended with an object of the type Stopwatch.

I joined MITAS because �e Graduate Programme


for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work helping foremen advis
he
International
al opportunities
Internationa
work
�ree woor placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
work
�ree wo or placements ssolve pr

153
JAVA 8:MULTITHREADED PROGRAMS Calendar

The above dialog box is called StopView and is a simple dialog box without a controller.
The dialog box is listening to the Stopwatch object.

Alarm and Timer


These two features are basically the same function, so I will mention them in the same place.

It has been decided that it should only be possible to start one alarm and one timer, and
that the two functions should not be persistent. That is, if there is set an alarm or started
a timer and the program is closed, the two functions state should not be saved and not
restarted if the application is opened again.

The timer is in principle a countdown, and it is decided to call this function a countdown.

If you in the toolbar click the alarm, you get the following window showing the current
time. You can then adjust the clock. If you click on start, the window closes and displays
an icon in the calendar’s lower right corner, indicating that there is set an alarm. When the
time of the alarm is triggered, you gets a warning as shown below, and the alarm function
is completed.

154
JAVA 8:MULTITHREADED PROGRAMS Calendar

If you click on the icon in the lower right corner opens the above dialog again:

where one can see the the amount of time to the alarm will occur and also can stop it.

If you choose the countdown you gets the same dialog boxes as above, and the difference
is only that the clock start is at 00:00:00 and you then set how long to wait before the
function gives a warning. In addition, a second icon in the lower right corner is shown.

To implement the two functions I have added an abstract class Watch to the model layer
used as a model for both an alarm and an countdown. The difference between an alarm
and a countdown is basically how to reset() the watch, and that something must be done
differently when the clock is started. When this occurs, a timer is started, that ticks every
second, and this timer is using a different timer function (TimerTask object), depending on
whether it is an alarm or a countdown, and the timer function must be implemented in
the concrete classes, called respectively Alarm and Counter. A Watch can fire events of type
TimeEvent which occurs when the clock is started, when the clock is stopped, when the
clock is updated, and when there is a timeout (the occurrence of an alarm or countdown
is timed out). In the latter case, it also means that the clock must stop. Listeners for these
events are defined by the TimeListener interface.

The class MainModel has objects of the types Alarm and Counter.

The same dialog box is used for both an alarm and a countdown, and the dialog box is
called WatchView.

155
JAVA 8:MULTITHREADED PROGRAMS Calendar

Appointments
The last feature in this iteration relating to appointments, and how to display a warning
when an appointment on the current day occurs. Compared to the requirements specification
is decided a change for when to display a warning. The reason is that the formulation in
the requirements specification can easily lead to too many warnings.

In order to display a warning, the appointment should be defined with a start time. A
warning should be displayed when:

1. 1 minute before the appointment starts


2. 5 minutes before the appointment starts
3. 15 minutes before the appointments starts
4. 1 hour before the appointment starts

A warning opens a popup that looks like the above, but there is a Cancel button. If you
click it, the warning does not appear again.

The logic regarding warnings for appointments is implemented in the class MainController.
Here the constructor starts a thread running in an infinite loop and every half minute
examines whether there are appointments for the current day, for which to display a reminder.

93%
OF MIM STUDENTS ARE
WORKING IN THEIR SECTOR 3 MONTHS
FOLLOWING GRADUATION

MASTER IN MANAGEMENT
• STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES
Length: 1O MONTHS
THAT THE CAPITAL OF SPAIN OFFERS
Av. Experience: 1 YEAR
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
Language: ENGLISH / SPANISH
PROFESSIONAL GOALS
Format: FULL-TIME
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
Intakes: SEPT / FEB
EXPERIENCE

5 Specializations #10 WORLDWIDE 55 Nationalities


MASTER IN MANAGEMENT
Personalize your program FINANCIAL TIMES
in class

www.ie.edu/master-management mim.admissions@ie.edu Follow us on IE MIM Experience

156
JAVA 8:MULTITHREADED PROGRAMS Calendar

11.4.5 ITERATION 5

The iteration starts as the other iterations and creates a copy of the NetBeans project from
the previous iteration. The copy is called Calendar6. It is a short iteration with only one
new dialog box, where the user must select a period for the calendar to be exported. The
calendar is exported in the controller for this dialog box. The iteration only adds to classes
to the project: ExportController that creates the file, and ExportView that is the dialog box.

11.4.6 ITERATION 6

Again the iteration starts to make a copy of the NetBeans project from the previous iteration.
The copy is called Calendar7. After this iteration the programming is finshed, and what is
back is the following:

1. A review of the overall look and feel.


2. Implementing of the function options (the last icon in the toolbar).
3. A code review and code documentation.

Look and feel


The goal of it is to get the individual dialogs to look the same, so they use the same colors
and fonts, and that the application of colors and fonts are consistent. Fonts and colors are
defined as constants in the class Options. The work is to go all dialog boxes through and
ensure consistent use of fonts and colors. Moreover, the colors are changed, so they are a
bit more neutral. Finally, some of the icons are replaced, and the result is a main window
as shown below:

157
JAVA 8:MULTITHREADED PROGRAMS Calendar

Options
If you click on the last icon in the toolbar you will get a popup menu with four menu items:

1. Data location
2. Delete notes
3. Delete appointments
4. Delete anniversaries

If the program is used over a longer period, the data file could be very large, especially if
there is stored many notes. There should be an option for deleting old data. The three delete
functions work in principle the same way, where you get a dialog box for entering two
dates, and so deleting all (notes, appointments or anniversaries) between these two dates.
The three dialog boxes are the same and are in principle the same dialog box as ExportView.
There is therefore written an abstract base class which all four dialogs inherit.

The file calendar.dat that contains the program’s data is created in the user’s home directory.
The goal of the first of the above functions is that the user must be able to choose the
directory where the file should be saved, and the same user can then use multiple calendars.
The path to the file must be stored somewhere, and it has been decided that it should be
in a hidden file (.pa_calendar) in the user’s home directory. The necessary programming to
change the directory is placed in the class DataAdapter. At the same time two of methods
are defined synchronized since there is a concurrency problem due to the thread, which tests
for appointments.

Code review
After the program is written and finished, I performs a code review. This work can take a
long time. Besides updating the comments and review the code the work also to address
directly errors and change inconveniences. In this case, I have changed the following.

The class MainDate is a wrapper class for a Date, and the class is not much more than a
very thin encapsulation of a Date. Originally the class was intended more functionality, but
since it is no longer the case, I have deleted the class. It means:

1. The class has three methods that tests whether a date is attached a note an
appointment or an anniversary. These three methods are moved to the class
MainModel as static methods.
2. All references in the class MainModel to MainDate are changed to Date.
3. All references in the class MainView to MainDate are changed to Date.

158
JAVA 8:MULTITHREADED PROGRAMS Calendar

Then the class MainDate is deleted. It is always dangerous to delete a class at the risk of
being overlooked something, but in this case it is simple since the class only is used in
MainModel and MainView and then the compiler wil find all the places where you has
to change.

The class MainView has a number of very simple inner classes that define event handlers
for click on an icon in the toolbar. Most of these classes are removed and replaced by
anonymous classes.

The class MainController is changed so that the thread that displays messages regarding
appointments start with deleting all appointments (those that must be deleted) that are
older than the current date. The reason is that if the program has not been used for several
days, there may otherwise be appointments that just remains and where time has passed.

159
JAVA
JAVA8:MULTITHREADED
8:MULTITHREADEDPROGRAMS
PROGRAMS Calendar
Calendar

11.5 TEST
11.5 TEST
Now
Now the
the program
program isis finished
finished and
and should
should be
be tested,
tested, and
and itit isis in
in this
this case
case aa quite
quite extensive
extensive
work to test the program. The following procedure can
work to test the program. The following procedure can be used:be used:

1.
1. The
The date
date file
file isis deleted
deleted manually.
manually.
2.
2. All
All test
test cases
cases fromfrom allall the
the iterations
iterations from
from the
the programming
programming are are used
used as
as test
test cases
cases
for the final test and are
for the final test and are performed.performed.
3.
3. The first
The first function
function in in the
the options
options menu
menu isis used
used toto changing
changing thethe location
location of of the
the
data
data file.
file.
4.
4. Create
Create twotwo notes
notes for for the
the current
current month,
month, anan anniversary
anniversary forfor the
the current
current month,
month, an an
appointment occurring within 3 minutes and an appointment
appointment occurring within 3 minutes and an appointment occurring within occurring within
½½ hour.
hour.
5.
5. Close
Close thethe program.
program.
6.
6. Open
Open the the program
program again. again.
7.
7. Test it looks right, especiallyon
Test it looks right, especially onthe
theoccurrence
occurrenceof ofwarnings
warningsfor forthe
thetwo
twoappointments.
appointments.
8. The data file is changed back to the first
8. The data file is changed back to the first data file. data file.
9.
9. Examines
Examines whether
whether everything
everything looks
looks right.
right.
10.
10. The
The three
three delete
delete functions
functions fromfrom the
the options
options menu
menu areare tested.
tested.

11.6 DELIVERY
11.6 DELIVERY
This
This time
time itit isis simple
simple toto deliver
deliver the
the program
program and and put
put itit into
into operation.
operation. There
There should
should only
only
be used the jar file and an icon. The installation script is similar to scripts as
be used the jar file and an icon. The installation script is similar to scripts as I have shown, I have shown,
and
and will
will not
not be be shown
shown here,
here, but
but the
the folder
folder setup
setup contains
contains the the following
following three
three files:
files:

1.
1. Calendar.jar
Calendar.jar
2. calendar.png
2. calendar.png
3.
3. calendar.sh
calendar.sh

where
where the
the last
last one
one isis the
the installation
installation script.
script. The
The program
program can
can then
then be
be installed
installed and
and put
put into
into
operation to executes the foolowing command from
operation to executes the foolowing command from a terminal: a terminal:

./calendar.sh

160
160
JAVA 8:MULTITHREADED PROGRAMS Appendix A

APPENDIX A
A virtual machine is a program that simulates a physical machine in software and the Java
runtime system is such a virtual machine. I will in this appendix provide a brief introduction
to what the Java virtual machine is and how it works.

Java’s virtual machine is called JVM for Java Virtual Machine, and you can think about it
as the engine that makes it possible to execute Java programs. It is a program (a machine)
that interprets and executes compiled Java programs. Other programming languages such
as C and C++ compiles directly to the specific platform, that is to a specific processor’s
instruction set and to a particular operating system, and the result is called executable code
that immediately can be carried out on the concrete machine without the assistance of a
virtual machine. This means other things being equal, tthat one gets more effective programs,
but there are also significant drawbacks. The main one is lack of portability, where the
translated program depends on the machine’s processor and operating system, and for the
program to run on a different platform, it must be translated again to the new environments.

All this talks of developing a platform independent programming language and it was one of
the main ideas that led to the development of Java. The principle is that the Java compiler
generates an optimized set of instructions, called bytecode. This code can not be directly
executed, since it consists of instructions to a machine that does not exist – instructions for
a virtual machine. For a program translated into bytecode to run, there must be running
a program on the machine, that simulates a machine whose instruction set is bytecode,
and such a program is exactly what JVM is. Platform independence consists in, that any
translated Java program can run on any machine that has a JVM running, and the translated
bytecode knows nothing about the physical machine’s processor or operating system.

As mentioned, the price of this platform independence and program execution by


interpretation of a virtual machine is performance. So it was, at least initially, but Java is
no longer a purely interpreted language, and most implementations of the JVM is today a
mixture of interpretation and execution of compiled code. This means that Java programs
today in practice has the same performance as programs whose code is translated into a
specific physical platform, also because the runtime system can perform a series of checks
and optimization, while the program runs.

161
JAVA 8:MULTITHREADED PROGRAMS Appendix A

It is also worth noting that Java includes an API called JNI, so you can use software modules
written in other languages like C and C++. The most important thing with JNI is that you
can use the system calls, which possibly not are directly accessible through Java. Finally, it
should be mentioned that JNI allows using routines written in C or C++ to situations where
the performance requirements are particularly critical. You should be aware that using JNI
means sacrificing the platform independence and the program becomes dependent on the
platform that the routines are translated to.

In order to achieve this platform independence JVM must be precise and well-defined,
which is done with a JVM specification which dictates the format of the bytecode and
defines the features and functionality that JVM must have. The specification is public and
can be found on Oracle’s website, and all can in principle write a JVM.

Excellent Economics and Business programmes at:

“The perfect start


of a successful,
international career.”

CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www.rug.nl/feb/education

162
JAVA 8:MULTITHREADED PROGRAMS Appendix A

JVM IMPLEMENTATIONS
There are several different implementations of JVM, and the most important is probably the
JVM from Sun Microsystems, and is often regarded as the reference implementation. After
Oracle acquired Sun, it is now their JVM, which is regarded as the reference implementation,
but there are certainly others who have implemented the JVM and including IBM, Apple
and Hewlett-Packard. However, does the specification of JVM, that Java programs will
behave the same regardless of which virtual machine they run on.

In 2006 changed Sun strategy from to control the standard and reference implementation
themself to instead to public an open model. This meant several things, including:

-- The full source code was made available to the public, or at least as much of it, as
Sun legally could publish because of licenses.
-- Changes and extensions of Java has subsequently been handled through the Java
Community Process (JCP) instead of inside Sun. JCP is an association which is
responsible for making decisions about how the language forward should be
developed, a development that Oracle has continued and now plays a key role in
the decision-making processes.
-- Today, is the reference implementation of Java an open source model, called Open
Java Development Kit and is designated OpenJDK.

THE RUNTIME SYSTEM


Every time you perform a Java application the program executes in fact an instance of JVM,
and each program has its own JVM instance. A Java program is translated into bytecode,
which as stated are instructions for a virtual machine, but these instructions must necessarily
somewhere be translated into instructions that the current platform (CPU and operating
system) can perform. The translated Java program consists of class files, which mainly
contains bytecode, and when the program is executed, these class files are loaded of JVM,
which then translates (interprets) the bytecode into instructions for the current machine.
JVM can be broadly summarized as follows:

163
JAVA 8:MULTITHREADED PROGRAMS Appendix A

In addition JVM must use memory for the code and temporary data as local variables and
so on. The data are stored within the virtual machine’s address space:

The heap is an area of available memory and is used to allocate memory at runtime, and
it is for objects and arrays. When the program creates an object or an array, it allocates
the required memory on the heap, and it is created when the JVM starts. The space that
an object or an array uses exist as long as there is a reference to the object, and when it is
no longer the case, the space is automatically deallocated by the garbage collector. The JVM
specification does not tell how the heap will be implemented, and it is also depends on
the implementation where the amount of heap is fixed or may change accordance with the
demand, but is there not enough heap for a program, you get an OutOfMemoryError exception.

164
JAVA 8:MULTITHREADED PROGRAMS Appendix A

The stack is used to maintain information on the methods being performed, and every time
you call a method the runtime system creates an activation block on the stack, that contains
local variables, parameters and return value and the operand stack used by the runtime
system. An activation block is created when a method is called and removed again when
the method terminates for one reason or another. Each thread has its own stack, and for
each stack there is only one activation block which is active at a time, and it is the block
for the method the thread is currently performing. Just as for the heap tells the specification
nothing about how the stack must be implemented, and it can be both of fixed size or
expand dynamically, but requires a thread more stack than is available, the program will
stop with a StackOverflowError exception.

The method area is shared by all threads and are used for information on methods and
their bytecode, data fields and constructors.

JVM has registers in the same way as a physical machine. They reflect the virtual machine’s
current state and are constantly updated, as the code is executed. The main register is
perhaps the program counter which contains the address of the next JVM instruction to
be performed. Other data is a pointer to the method currently performed, a pointer to the
first local variable for the current method, and a pointer to the top of the operand stack.

American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

▶▶ enroll by September 30th, 2014 and


▶▶ save up to 16% on the tuition!
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

165
JAVA 8:MULTITHREADED PROGRAMS Appendix A

The last are constant pool and is used for constants.

Then there is the garbage collector. As mentioned allocates Java automatic memory to an object
when it is created with new, and the allocated memory is again deallocated automatically
when there are no longer references to the object. Everything is handled by the garbage
collector, which is a program that constantly runs and will manages the heap. This is done
using a table of pointers that point to the individual objects on the heap. We call these
pointers for soft pointers, because instead of pointing directly at the concrete objects they
points to the object’s references. The garbage collector runs in the background in its own
thread and performs periodically checking the object’s state, and when there are no longer
references to an object, the space which the object has used on the heap is released, and
the pointer is removed from the table. When the runtime system continuously allocates
objects and deallocates them again, the heap may be fragmented, and if it happens the
garbage collector defragments the heap (which means that the objects are move) and thus
gather all the available space on the heap in a large contiguous area. It is from there that
garbage the collector takes its name.

166

Anda mungkin juga menyukai