Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
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

Immutability

Immutable objects are thread-safe. When an object is immutable, you cannot make changes to the object. Many threads can read the object at the same time and when a thread needs to change a value, it creates a modified copy. For example, Java strings are immutable. Consider the following code snippet: 

import java.util.HashSet;
import java.util.Set;

public class StringsAreImmutable {
public static void main(String[] args) {
String s = "Hi friends!";
s.toUpperCase();
System.out.println(s);

String s1 = s.toUpperCase();
System.out.println(s1);

String s2 = s1;
String s3 = s1;
String s4 = s1;

Set set = new HashSet<String>();
set.add(s);
set.add(s1);
set.add(s2);
set.add(s3);

System.out.println(set);
}
}

Running the code gives the following output:

Hi friends!
HI FRIENDS!
[Hi friends!, HI FRIENDS!]

When...

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