Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Concurrent Patterns and Best Practices

You're reading from   Concurrent Patterns and Best Practices Build scalable apps in Java with multithreading, synchronization and functional programming patterns

Arrow left icon
Product type Paperback
Published in Sep 2018
Publisher Packt
ISBN-13 9781788627900
Length 264 pages
Edition 1st Edition
Languages
Concepts
Arrow right icon
Author (1):
Arrow left icon
Atul S. Khot Atul S. Khot
Author Profile Icon Atul S. Khot
Atul S. Khot
Arrow right icon
View More author details
Toc

Active objects

Here is a classic problem given a piece of legacy code written without any threading consideration. How do we make it thread-safe?

The following class illustrates this problem:

private class LegacyCode {
int x;
int y;

public LegacyCode(int x, int y) {
this.x = x;
this.y = y;
}
// setters and getters are skipped
// they are there though

There are two methods, m1() and m2(), which change the instance state in some way. Here is the m1() method:

public void m1() {
setX(9);
setY(0);
}

It sets the x field to 9 and the y field to 0:

public void m2() {
setY(0);
setX(9);
}

 The m2() method does the opposite: it sets x to 0 and y to 9. 

If we try to make this class concurrent, using threads, you know we need to carefully synchronize access to all shared states.  Of course, any legacy code has many other ramifications...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image