SlideShare a Scribd company logo
1 of 20
Download to read offline
codecentric AG
Dusan Zamurovic
A pattern discussion
codecentric AG
 Singleton pattern
 things we sometimes forget
 Dependency injection / Inversion of Control
 Paired with Singleton
 Example without third party library
TOPICS
codecentric AG
 What Singleton pattern does?
 Implementation examples
 Wrong implementations
 Implementations that look okay
 Right implementations
Singleton
codecentric AG
Singleton 01
public class Singleton01 {
// TODO Make this class final?
private static Singleton01 instance = null;
private Singleton01() {
// Private constructor prevents instantiation,
// but also prevents sub-classing.
}
public static Singleton01 getInstance() {
if (instance == null) {
instance = new Singleton01();
}
return instance;
}
}
codecentric AG
Singleton 02
private static Singleton02 instance = null;
public static Singleton02 getInstance() {
if (instance == null) {
simulateMultiThreadEnvironment();
instance = new Singleton02();
}
return instance;
}
// Not synchronized, not thread safe.
codecentric AG
Singleton 03
private static Singleton03 instance = null;
public synchronized static Singleton03 getInstance() {
if (instance == null) {
simulateMultiThreadEnvironment();
instance = new Singleton03();
}
return instance;
}
// Synchronized, thread safe.
codecentric AG
Singleton 04
private static Singleton04 instance = null;
public static Singleton04 getInstance() {
if (instance == null) {
synchronized (Singleton04.class) {
simulateMultiThreadEnvironment();
instance = new Singleton04();
}
}
return instance;
}
// Synchronized, performance optimization, not thread safe.
codecentric AG
Singleton 05
private static Singleton05 instance = null;
public static Singleton05 getInstance() {
if (instance == null) {
synchronized (Singleton05.class) {
if (instance == null) {
instance = new Singleton05();
}
}
}
return instance;
}
// Double-checked locking – doesn’t work prior to Java 1.5.
codecentric AG
Singleton 06
private static final Singleton06 INSTANCE = new Singleton06();
public static Singleton06 getInstance() {
return INSTANCE;
}
// Eager instantiating of the class. This works.
// What about serialization/deserialization?
codecentric AG
Singleton 06 Serializable
public class Singleton06 implements Serializable {
private static final Singleton06 INSTANCE = new Singleton06();
public static Singleton06 getInstance() {
return INSTANCE;
}
}
protected Object readResolve() {
return getInstance();
}
codecentric AG
Singleton 07
public enum Singleton07 {
INSTANCE;
}
// What about serialization/deserialization?
// What about reflection?
codecentric AG
 What is DI / IoC?
 Implementation example
 No third party library
Dependency Injection / Inversion of Control
codecentric AG
Dependency Injection / Inversion of Control
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Inject {
}
// @Component is used to mark a class – a thing to inject.
// @Inject is used to mark a field – a place to inject.
codecentric AG
Dependency Injection / Inversion of Control
@Component
public class Controller {
@Inject
private ManageCapable manager;
…
}
@Component
public class Manager implements ManageCapable {
@Inject
private Repository repository;
…
}
codecentric AG
Dependency Injection / Inversion of Control
@Component
public class Repository {
public Resourcable save(Resourcable aResource) {
// Here we "persist" the given resource
// and return it like we really did it.
return aResource;
}
}
codecentric AG
Dependency Injection / Inversion of Control
public class PackageScanner {
…
}
public class ClassScanner {
…
}
public class DependencyInjectionManager {
…
}
// https://github.com/dzamurovic/meetup_singleton.git
codecentric AG
Dependency Injection / Inversion of Control
public synchronized void run() throws Exception {
if (initialized) {
return;
}
// Find classes annotated with @Component.
List<Class> components = packageScanner.findAnnotatedClasses(
"rs.codecentric.meetup.diioc.example", Component.class);
// For each component...
for (Class component : components) {
Class definingClass = classScanner.getDefiningClass(component);
// ... check if its instance already exists...
if (!graph.containsKey(definingClass)) {
// ... and instantiate it, if it doesn't.
String className = component.getName();
graph.put(definingClass, Class.forName(component.getName()).newInstance());
}
}
}
codecentric AG
Dependency Injection / Inversion of Control
// For each object that is created...
for (Iterator<Class> classIterator = graph.keySet().iterator();
classIterator.hasNext();) {
Class definingClass = classIterator.next();
Object object = graph.get(definingClass);
// ... find dependencies it needs, ...
for (Field f : classScanner.findAnnotatedFields(object.getClass(),
Inject.class)) {
if (!graph.containsKey(f.getType())) {
// ... throw an error if a dependency cannot be satisfied, ...
}
// ... or set a value of the dependency.
Object dependency = graph.get(f.getType());
f.set(object, dependency);
}
}
initialized = true;
}
codecentric AG
Dependency Injection / Inversion of Control
public static void main(String args[]) throws Exception {
final DependencyInjectionManager diManager =
DependencyInjectionManager.getInstance();
Thread t1 = new DependencyInjectionThread("DI-thread-0", diManager);
Thread t2 = …
t1.start();
t2.st…
t1.join();
t2.j…
diManager.describeDependencyGraph();
}
codecentric AG
QUESTIONS?
https://github.com/dzamurovic/meetup_singleton.git
dusan.zamurovic@codecentric.de
@ezamur
@CodingSerbia
http://www.meetup.com/Coding-Serbia/
www.codecentric.de
www.codecentric.rs
https://blog.codecentric.de
6/27/2014 20

More Related Content

What's hot

Java Serialization
Java SerializationJava Serialization
Java Serializationjeslie
 
Unit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftUnit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftallanh0526
 
Using ReasonML For Your Next JavaScript Project
Using ReasonML For Your Next JavaScript ProjectUsing ReasonML For Your Next JavaScript Project
Using ReasonML For Your Next JavaScript ProjectRoy Derks
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksSamundra khatri
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mockPranalee Rokde
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 
Looking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelopLooking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelopPVS-Studio
 
A fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBoxA fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBoxPVS-Studio
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 KotlinVMware Tanzu
 
Java Libraries You Can't Afford to Miss
Java Libraries You Can't Afford to MissJava Libraries You Can't Afford to Miss
Java Libraries You Can't Afford to MissAndres Almiray
 
Linq & lambda overview C#.net
Linq & lambda overview C#.netLinq & lambda overview C#.net
Linq & lambda overview C#.netDhairya Joshi
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
Padroes Projeto
Padroes ProjetoPadroes Projeto
Padroes Projetolcbj
 

What's hot (20)

CDI: How do I ?
CDI: How do I ?CDI: How do I ?
CDI: How do I ?
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Mockito
MockitoMockito
Mockito
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Unit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftUnit testing in xcode 8 with swift
Unit testing in xcode 8 with swift
 
Using ReasonML For Your Next JavaScript Project
Using ReasonML For Your Next JavaScript ProjectUsing ReasonML For Your Next JavaScript Project
Using ReasonML For Your Next JavaScript Project
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Looking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelopLooking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelop
 
A fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBoxA fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBox
 
Power mock
Power mockPower mock
Power mock
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
 
Java Libraries You Can't Afford to Miss
Java Libraries You Can't Afford to MissJava Libraries You Can't Afford to Miss
Java Libraries You Can't Afford to Miss
 
Linq & lambda overview C#.net
Linq & lambda overview C#.netLinq & lambda overview C#.net
Linq & lambda overview C#.net
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Control statements
Control statementsControl statements
Control statements
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Padroes Projeto
Padroes ProjetoPadroes Projeto
Padroes Projeto
 

Similar to Meetup - Singleton & DI/IoC

Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Arsen Gasparyan
 
RIBs - Fragments which work
RIBs - Fragments which workRIBs - Fragments which work
RIBs - Fragments which workDmitry Zaytsev
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objectsSandeep Chawla
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConos890
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)David McCarter
 
Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Sameer Rathoud
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805LearningTech
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805LearningTech
 
Singleton Pattern
Singleton PatternSingleton Pattern
Singleton PatternHany Omar
 
It's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journeyIt's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journeyThiago “Fred” Porciúncula
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Oliver Gierke
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonJonathan Simon
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsRavi Bhadauria
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014First Tuesday Bergen
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014Matthias Noback
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentJayaprakash R
 

Similar to Meetup - Singleton & DI/IoC (20)

Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
 
RIBs - Fragments which work
RIBs - Fragments which workRIBs - Fragments which work
RIBs - Fragments which work
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheCon
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
 
Singleton Pattern
Singleton PatternSingleton Pattern
Singleton Pattern
 
It's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journeyIt's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journey
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and Singleton
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 
Dependency Injection for Android
Dependency Injection for AndroidDependency Injection for Android
Dependency Injection for Android
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 

Recently uploaded

Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...kalichargn70th171
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdfAndrey Devyatkin
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdfSteve Caron
 
Advantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxAdvantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxRTS corp
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 

Recently uploaded (20)

Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
 
Advantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxAdvantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptx
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 

Meetup - Singleton & DI/IoC

  • 1. codecentric AG Dusan Zamurovic A pattern discussion
  • 2. codecentric AG  Singleton pattern  things we sometimes forget  Dependency injection / Inversion of Control  Paired with Singleton  Example without third party library TOPICS
  • 3. codecentric AG  What Singleton pattern does?  Implementation examples  Wrong implementations  Implementations that look okay  Right implementations Singleton
  • 4. codecentric AG Singleton 01 public class Singleton01 { // TODO Make this class final? private static Singleton01 instance = null; private Singleton01() { // Private constructor prevents instantiation, // but also prevents sub-classing. } public static Singleton01 getInstance() { if (instance == null) { instance = new Singleton01(); } return instance; } }
  • 5. codecentric AG Singleton 02 private static Singleton02 instance = null; public static Singleton02 getInstance() { if (instance == null) { simulateMultiThreadEnvironment(); instance = new Singleton02(); } return instance; } // Not synchronized, not thread safe.
  • 6. codecentric AG Singleton 03 private static Singleton03 instance = null; public synchronized static Singleton03 getInstance() { if (instance == null) { simulateMultiThreadEnvironment(); instance = new Singleton03(); } return instance; } // Synchronized, thread safe.
  • 7. codecentric AG Singleton 04 private static Singleton04 instance = null; public static Singleton04 getInstance() { if (instance == null) { synchronized (Singleton04.class) { simulateMultiThreadEnvironment(); instance = new Singleton04(); } } return instance; } // Synchronized, performance optimization, not thread safe.
  • 8. codecentric AG Singleton 05 private static Singleton05 instance = null; public static Singleton05 getInstance() { if (instance == null) { synchronized (Singleton05.class) { if (instance == null) { instance = new Singleton05(); } } } return instance; } // Double-checked locking – doesn’t work prior to Java 1.5.
  • 9. codecentric AG Singleton 06 private static final Singleton06 INSTANCE = new Singleton06(); public static Singleton06 getInstance() { return INSTANCE; } // Eager instantiating of the class. This works. // What about serialization/deserialization?
  • 10. codecentric AG Singleton 06 Serializable public class Singleton06 implements Serializable { private static final Singleton06 INSTANCE = new Singleton06(); public static Singleton06 getInstance() { return INSTANCE; } } protected Object readResolve() { return getInstance(); }
  • 11. codecentric AG Singleton 07 public enum Singleton07 { INSTANCE; } // What about serialization/deserialization? // What about reflection?
  • 12. codecentric AG  What is DI / IoC?  Implementation example  No third party library Dependency Injection / Inversion of Control
  • 13. codecentric AG Dependency Injection / Inversion of Control @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Component { } @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Inject { } // @Component is used to mark a class – a thing to inject. // @Inject is used to mark a field – a place to inject.
  • 14. codecentric AG Dependency Injection / Inversion of Control @Component public class Controller { @Inject private ManageCapable manager; … } @Component public class Manager implements ManageCapable { @Inject private Repository repository; … }
  • 15. codecentric AG Dependency Injection / Inversion of Control @Component public class Repository { public Resourcable save(Resourcable aResource) { // Here we "persist" the given resource // and return it like we really did it. return aResource; } }
  • 16. codecentric AG Dependency Injection / Inversion of Control public class PackageScanner { … } public class ClassScanner { … } public class DependencyInjectionManager { … } // https://github.com/dzamurovic/meetup_singleton.git
  • 17. codecentric AG Dependency Injection / Inversion of Control public synchronized void run() throws Exception { if (initialized) { return; } // Find classes annotated with @Component. List<Class> components = packageScanner.findAnnotatedClasses( "rs.codecentric.meetup.diioc.example", Component.class); // For each component... for (Class component : components) { Class definingClass = classScanner.getDefiningClass(component); // ... check if its instance already exists... if (!graph.containsKey(definingClass)) { // ... and instantiate it, if it doesn't. String className = component.getName(); graph.put(definingClass, Class.forName(component.getName()).newInstance()); } } }
  • 18. codecentric AG Dependency Injection / Inversion of Control // For each object that is created... for (Iterator<Class> classIterator = graph.keySet().iterator(); classIterator.hasNext();) { Class definingClass = classIterator.next(); Object object = graph.get(definingClass); // ... find dependencies it needs, ... for (Field f : classScanner.findAnnotatedFields(object.getClass(), Inject.class)) { if (!graph.containsKey(f.getType())) { // ... throw an error if a dependency cannot be satisfied, ... } // ... or set a value of the dependency. Object dependency = graph.get(f.getType()); f.set(object, dependency); } } initialized = true; }
  • 19. codecentric AG Dependency Injection / Inversion of Control public static void main(String args[]) throws Exception { final DependencyInjectionManager diManager = DependencyInjectionManager.getInstance(); Thread t1 = new DependencyInjectionThread("DI-thread-0", diManager); Thread t2 = … t1.start(); t2.st… t1.join(); t2.j… diManager.describeDependencyGraph(); }

Editor's Notes

  1. 1. Thread A notices that the value is not initialized, so it obtains the lock and begins to initialize the value. 2. The code generated by the compiler is allowed to update the shared variable to point to a partially constructed object before A has finished performing the initialization. 3. Thread B notices that the shared variable has been initialized (or so it appears), and returns its value. Because thread B believes the value is already initialized, it does not acquire the lock. If B uses the object before all of the initialization done by A is seen by B the program will likely crash.