+ All Categories
Home > Software > Singleton in multithreaded environment

Singleton in multithreaded environment

Date post: 15-Jun-2015
Category:
Upload: talha-ocakci
View: 232 times
Download: 6 times
Share this document with a friend
Description:
Making the constructor private and using a static getter method only, your singleton object will not be able to survive in multi-thread or multi CPU environment. We will look for a soluton to singleton usage problem in multithread environment. First attempt will be double-locking mechanism, then we will use volatile keyword to complete the task. This is a production of www.javathlon.com. Happy learning.
Popular Tags:
14
SINGLETON PATTERN Fall of double check by Talha Ocakçı
Transcript
Page 1: Singleton in multithreaded environment

SINGLETON PATTERNFall of double check

by Talha Ocakçı

Page 2: Singleton in multithreaded environment

GOAL of SINGLETON PATTERN

Using the same instance throughout the application. When we want to

● Use huge objects without-recreating● Centralizing a process

Page 3: Singleton in multithreaded environment

HOW TO CREATEThe simplest form

1 - Define a static instance of itself inside the class, initialize it as null

2- Make the constructor private

3- Define a getInstance method, call the constructor if the inner instance is null

Page 4: Singleton in multithreaded environment

Simplest implementation

Page 5: Singleton in multithreaded environment

Race condition in multithread

Thread 1Thread 2

Page 6: Singleton in multithreaded environment

Race condition in multithread

Thread 1

Thread 2

Page 7: Singleton in multithreaded environment

Race condition in multithread

Thread 1

Thread 2

Page 8: Singleton in multithreaded environment

Race condition in multithread

Thread 1

Thread 2

Page 9: Singleton in multithreaded environment

Java Memory Management Problem

Object creation with new keyword has several non-atomic hidden operations.

Page 10: Singleton in multithreaded environment

Object creation

1- Allocate memory

2- Use stack space for related address

3- Initialize object

4- Flush the values to common memory

Page 11: Singleton in multithreaded environment

What is flushing?

Flushing means, writing a modified object’s state to common memory area

Page 12: Singleton in multithreaded environment

volatile object creation

1- Allocate memory

2- Use stack space for related address

3- Initialize object

4- Flush the values to common memory

volatile, makes the object modification an atomic process

Page 13: Singleton in multithreaded environment

Latest version

Page 14: Singleton in multithreaded environment

Thanks for checking the presentation.You may access the video that is explaining this presentation on http://youtu.be/zUYLY8kYavsand similar tutorials on

www.javathlon.com


Recommended