Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.myapp.patterns.creational;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- public class TestSingleton {
- private static TestSingleton instance=null;
- private TestSingleton() {
- // TODO Auto-generated constructor stub
- }
- public static TestSingleton getInstance(){
- synchronized (TestSingleton.class) {
- if(instance == null){
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- instance=new TestSingleton();
- }
- return instance;
- }
- }
- private static final String url="jdbc:mysql://localhost:3306/citrix";
- private static final String username="admin";
- private static final String password="admin";
- private Connection connection=null;
- public Connection getConnection() throws SQLException{
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- if(connection==null || connection.isClosed()){
- synchronized (TestSingleton.class) {
- if(connection==null || connection.isClosed()){
- connection=DriverManager.getConnection(url, username, password);
- }
- }
- }
- return connection;
- }
- static TestSingleton instance1=null;
- static TestSingleton instance2=null;
- public static void main(String[] args) {
- Runnable task1=()->{
- instance1=TestSingleton.getInstance();
- };
- Runnable task2=()->{
- instance2=TestSingleton.getInstance();
- };
- Thread t1=new Thread(task1);
- Thread t2=new Thread(task2);
- t1.start();
- t2.start();
- try {
- t1.join();
- t2.join();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(instance1 == instance2);
- try {
- Connection con1=instance1.getConnection();
- Connection con2=instance2.getConnection();
- System.out.println(con1==con2);
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
Add Comment
Please, Sign In to add comment