Singleton in multithreaded environment

Post on 15-Jun-2015

232 views 6 download

Tags:

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.

transcript

SINGLETON PATTERNFall of double check

by Talha Ocakçı

GOAL of SINGLETON PATTERN

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

● Use huge objects without-recreating● Centralizing a process

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

Simplest implementation

Race condition in multithread

Thread 1Thread 2

Race condition in multithread

Thread 1

Thread 2

Race condition in multithread

Thread 1

Thread 2

Race condition in multithread

Thread 1

Thread 2

Java Memory Management Problem

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

Object creation

1- Allocate memory

2- Use stack space for related address

3- Initialize object

4- Flush the values to common memory

What is flushing?

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

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

Latest version

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