SlideShare una empresa de Scribd logo
1 de 20
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

Más contenido relacionado

La actualidad más candente

Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
Richard Paul
 
Padroes Projeto
Padroes ProjetoPadroes Projeto
Padroes Projeto
lcbj
 

La actualidad más candente (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 a Meetup - Singleton & DI/IoC

Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
LearningTech
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
LearningTech
 

Similar a 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
 

Último

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 

Último (20)

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 

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(); }

Notas del editor

  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.