File: VirtuosoConnectionPoolDataSource.java

package info (click to toggle)
virtuoso-opensource 6.1.6%2Bdfsg2-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 260,060 kB
  • ctags: 123,765
  • sloc: ansic: 652,532; sql: 458,419; xml: 282,834; java: 61,031; sh: 40,031; cpp: 36,890; cs: 25,240; php: 12,692; yacc: 9,523; lex: 7,018; makefile: 6,157; jsp: 4,484; awk: 1,643; perl: 1,013; ruby: 1,003; python: 326
file content (894 lines) | stat: -rw-r--r-- 25,714 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
/*
 *  $Id$
 *
 *  This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
 *  project.
 *
 *  Copyright (C) 1998-2012 OpenLink Software
 *
 *  This project is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License as published by the
 *  Free Software Foundation; only version 2 of the License, dated June 1991.
 *
 *  This program is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 *
 */

package virtuoso.jdbc2;

import java.lang.reflect.*;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.Connection;
import java.io.Serializable;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.List;
import java.util.TreeSet;
import javax.sql.*;
import javax.naming.*;

public class VirtuosoConnectionPoolDataSource
    extends VirtuosoDataSource
    implements ConnectionPoolDataSource, ConnectionEventListener {

    protected final static String n_minPoolSize = "minPoolSize";
    protected final static String n_maxPoolSize = "maxPoolSize";
    protected final static String n_initialPoolSize = "initialPoolSize";
    protected final static String n_maxIdleTime = "maxIdleTime";
    protected final static String n_propertyCycle = "propertyCycle";
    protected final static String n_maxStatements = "maxStatements";

    public int minPoolSize = 0;
    public int maxPoolSize = 0;
    public int initialPoolSize = 0;
    public int maxIdleTime = 0;
    public int propertyCycle = 0;
    public int maxStatements = 0;

    private ConnCache connPool;
    private boolean isInitialized = false;
    private boolean isClosed = false;
    private Object  initLock ;
#if JDK_VER >= 16
    private TreeSet<Object> propQueue;
#else
    private TreeSet propQueue;
#endif
    private long  propEnforceTime = 0;


  public synchronized void finalize () throws Throwable {
    close ();
  }


  public VirtuosoConnectionPoolDataSource() {
    dataSourceName = "VirtuosoConnectionPoolDataSourceName";
    initLock = new Object();
    connPool = new ConnCache(this);
#if JDK_VER >= 16
    propQueue = new TreeSet<Object>( new Comparator<Object>() {
#else
    propQueue = new TreeSet( new Comparator() {
#endif
          public int compare(Object a, Object b) {
            long a_time = ((NewProperty)a).enforceTime;
            long b_time = ((NewProperty)b).enforceTime;
            if (a_time == b_time)
              return 0;
            else if (a_time > b_time)
              return +1;
            else
              return -1;
          }
        });
  }


  protected void checkPool() {
    if (isClosed)
       return;

    connPool.checkPool();
  }


  protected void checkPropQueue() {
    if (isClosed || propEnforceTime == 0)
       return;

    long curTime = System.currentTimeMillis();
    NewProperty prop;
    synchronized(propQueue) {
      while(propEnforceTime != 0 && propEnforceTime < curTime) {
        try {
          prop = (NewProperty)(propQueue.first());
        } catch (NoSuchElementException e) {
          propEnforceTime = 0;
          break;
        }
        propQueue.remove(prop);
        try {
          prop.fld.setInt(this, prop.arg);
        } catch (Exception e) {
          //?? System.out.println(e);
        }
        try {
          prop = (NewProperty)(propQueue.first());
          propEnforceTime = prop.enforceTime;
        } catch (NoSuchElementException e) {
          propEnforceTime = 0;
          break;
        }
      }
    }
  }


  /**
   * Physically close all the pooled connections in the cache and free all
   * the resources
   *
   * @exception  java.sql.SQLException
   *             if a database-access error occurs
   *
  **/
  public void close() throws SQLException {
    if (isClosed)
      return;

    isClosed = true;
    connPool.clear();
    initLock = null;
    propQueue.clear();
  }


//==================== interface ConnectionEventListener
  /**
   * Invoked when the application calls close() on its representation of
   * the connection.
   *
   * @param event an event object describing the source of the event
  **/
  public void connectionClosed(ConnectionEvent event) {
    try {
      Object source = event.getSource();
      if (source instanceof VirtuosoPooledConnection)
        connPool.reusePooledConnection((VirtuosoPooledConnection)event.getSource());
    } catch(SQLException e) { }
  }


  /**
   * Invoked when a fatal connection error occurs, just before an SQLException
   * is thrown to the application.
   *
   * @param event an event object describing the source of the event
  **/
  public void connectionErrorOccurred(ConnectionEvent event) {
    try {
      Object source = event.getSource();
      if (source instanceof VirtuosoPooledConnection)
        connPool.closePooledConnection((VirtuosoPooledConnection)event.getSource());
    } catch(SQLException e) { }
  }


//==================== interface Referenceable
  protected void  addProperties(Reference ref) {
    super.addProperties(ref);

    //Pool Specific
    ref.add(new StringRefAddr(VirtuosoConnectionPoolDataSource.n_minPoolSize, String.valueOf(minPoolSize)));
    ref.add(new StringRefAddr(VirtuosoConnectionPoolDataSource.n_maxPoolSize, String.valueOf(maxPoolSize)));
    ref.add(new StringRefAddr(VirtuosoConnectionPoolDataSource.n_initialPoolSize, String.valueOf(initialPoolSize)));
    ref.add(new StringRefAddr(VirtuosoConnectionPoolDataSource.n_maxIdleTime, String.valueOf(maxIdleTime)));
    ref.add(new StringRefAddr(VirtuosoConnectionPoolDataSource.n_propertyCycle, String.valueOf(propertyCycle)));
    ref.add(new StringRefAddr(VirtuosoConnectionPoolDataSource.n_maxStatements, String.valueOf(maxStatements)));
  }


  public Reference getReference() throws NamingException {
#if JDK_VER < 14
     Reference ref = new Reference(getClass().getName(), "virtuoso.jdbc2.VirtuosoDataSourceFactory", null);
#elif JDK_VER < 16
     Reference ref = new Reference(getClass().getName(), "virtuoso.jdbc3.VirtuosoDataSourceFactory", null);
#else
     Reference ref = new Reference(getClass().getName(), "virtuoso.jdbc4.VirtuosoDataSourceFactory", null);
#endif
     addProperties(ref);
     return ref;
  }


  /**
   * Fills the cache with PooledConnections for later use.
   * Ignored if the MinPoolSize is 0.
   * It is usually called when the OPLConnectionPoolDataSource is created
   * via JNDI calls.
   *
   * @exception  java.sql.SQLException
   *             if a error occurs
  **/
  public void fill() throws java.sql.SQLException {
    check_close();
    Properties info = createConnProperties();
    String connKey = create_url_key(create_url(), info);

    synchronized(initLock) {
      if (!isInitialized) {
        isInitialized = true;
        if (initialPoolSize == 0)
          initialPoolSize = minPoolSize;
        if (initialPoolSize != 0) {
          OpenHelper initThread = new OpenHelper(initialPoolSize, info);
          initThread.start();
          try {
            initThread.join();
          }
          catch (InterruptedException e) {}
        }
        VirtuosoPoolManager.getInstance().addPool(this);
      }

    }
  }

  /**
   * Attempt to get a database connection from the pool or
   * to establish a database connection .
   *
   * @return   a Connection to the database
   *
   * @exception  java.sql.SQLException
   *             if a database-access error occurs
  **/
  public Connection getConnection() throws java.sql.SQLException {
    return getPooledConnection().getConnection();
  }


  /**
   * Attempt to get a database connection from the pool or
   * to establish a database connection .
   *
   * @param   user       the database user on whose behalf the Connection is being made
   * @param   password   the user's password
   *
   * @return   a Connection to the database
   *
   * @exception  java.sql.SQLException
   *             if a database-access error occurs
  **/
  public Connection getConnection(String user, String password) throws java.sql.SQLException {
    return getPooledConnection(user, password).getConnection();
  }

  /**
   * Attempt to establish a database connection.
   *
   * @return   a PooledConnection to the database
   *
   * @exception  java.sql.SQLException
   *             if a database-access error occurs
  **/
  public PooledConnection getPooledConnection() throws java.sql.SQLException {
    return getPooledConnection(null, null);
  }


  /**
   * Attempts to establish a physical database connection that can
   * be used as a pooled connection.
   *
   * @param   user       the database user on whose behalf the Connection is being made
   * @param   password   the user's password
   *
   * @return   a PooledConnection to the database
   *
   * @exception  java.sql.SQLException
   *             if a database-access error occurs
  **/
  public PooledConnection getPooledConnection(String _user, String _password)
      throws java.sql.SQLException
  {
    check_close();
    String conn_url = create_url();
    Properties info = createConnProperties();

    if (_user != null)
        info.setProperty("user", _user);
    if (_password != null)
        info.setProperty("password", _password);

    String connKey = create_url_key(conn_url, info);
    Connection conn;

    synchronized(initLock) {
      if (!isInitialized) {
        isInitialized = true;
        if (initialPoolSize == 0)
          initialPoolSize = minPoolSize;
        if (initialPoolSize != 0) {
          OpenHelper initThread = new OpenHelper(initialPoolSize, info);
          initThread.start();
          try {
             initThread.join();
          } catch(InterruptedException e) {}
        }
        VirtuosoPoolManager.getInstance().addPool(this);
      }
    }

    return connPool.getPooledConnection(info, connKey, conn_url);

  }


  // get & set methods
  // PooledSpecific
  /**
   * Get the minimum number of physical connections
   * the pool will keep available at all times. Zero ( 0 ) indicates that
   * connections will be created as needed.
   *
   * @return   the minimum number of physical connections
   *
  **/
  public int getMinPoolSize() {
    return minPoolSize;
  }

  /**
   * Set the number of physical connections the pool should keep available
   * at all times. Zero ( 0 ) indicates that connections should be created
   * as needed
   * The default value is 0 .
   *
   * @param   parm a minimum number of physical connections
   *
   * @exception  java.sql.SQLException if an error occurs
   *
  **/
  public void setMinPoolSize(int parm) throws SQLException
  {
    try {
      Field fld = getClass().getField(this.n_minPoolSize);
      setField(fld, parm);
    } catch (Exception e) {
      throw new VirtuosoException("Error: "+e.toString(), VirtuosoException.OK);
    }
  }



  /**
   * Get the maximum number of physical connections
   * the pool will be able contain. Zero ( 0 ) indicates no maximum size.
   *
   * @return   the maximum number of physical connections
   *
  **/
  public int getMaxPoolSize() {
    return maxPoolSize;
  }

  /**
   * Set the maximum number of physical conections that the pool should contain.
   * Zero ( 0 ) indicates no maximum size.
   * The default value is 0 .
   *
   * @param   parm a maximum number of physical connections
   *
   * @exception  java.sql.SQLException if an error occurs
   *
  **/
  public void setMaxPoolSize(int parm) throws SQLException
  {
    try {
      Field fld = getClass().getField(this.n_maxPoolSize);
      setField(fld, parm);
    } catch (Exception e) {
      throw new VirtuosoException("Error: "+e.toString(), VirtuosoException.OK);
    }
  }


  /**
   * Get the number of physical connections the pool
   * will contain when it is created
   *
   * @return   the number of physical connections
   *
  **/
  public int getInitialPoolSize() {
    return initialPoolSize;
  }

  /**
   * Set the number of physical connections the pool
   * should contain when it is created
   *
   * @param   parm a number of physical connections
   *
   * @exception  java.sql.SQLException if an error occurs
   *
  **/
  public void setInitialPoolSize(int parm) throws SQLException
  {
    try {
      Field fld = getClass().getField(this.n_initialPoolSize);
      setField(fld, parm);
    } catch (Exception e) {
      throw new VirtuosoException("Error: "+e.toString(), VirtuosoException.OK);
    }
  }


  /**
   * Get the number of seconds that a physical connection
   * will remain unused in the pool before the
   * connection is closed. Zero ( 0 ) indicates no limit.
   *
   * @return   the number of seconds
  **/
  public int getMaxIdleTime() {
    return maxIdleTime;
  }

  /**
   * Set the number of seconds that a physical connection
   * should remain unused in the pool before the
   * connection is closed. Zero ( 0 ) indicates no limit.
   *
   * @param  parm a number of seconds
   *
   * @exception  java.sql.SQLException if an error occurs
   *
  **/
  public void setMaxIdleTime(int parm) throws SQLException
  {
    try {
      Field fld = getClass().getField(this.n_maxIdleTime);
      setField(fld, parm);
    } catch (Exception e) {
      throw new VirtuosoException("Error: "+e.toString(), VirtuosoException.OK);
    }
  }

  /**
   * Get the interval, in seconds, that the pool will wait
   * before enforcing the current policy defined by the
   * values of the above connection pool properties
   *
   * @return  the interval (in seconds)
  **/
  public int getPropertyCycle() {
    return propertyCycle;
  }

  /**
   * Set the interval, in seconds, that the pool should wait
   * before enforcing the current policy defined by the
   * values of the above connection pool properties
   *
   * @param  parm an interval (in seconds)
  **/
  public void setPropertyCycle(int parm) {
    propertyCycle = parm;
  }


  /**
   * Get the total number of statements that the pool will
   * keep open. Zero ( 0 ) indicates that caching of
   * statements is disabled.
   *
   * @return  the total number of statements
  **/
  public int getMaxStatements() {
    return maxStatements;
  }

  /**
   * Set the total number of statements that the pool should
   * keep open. Zero ( 0 ) indicates that caching of
   * statements is disabled.
   *
   * @param  parm a total number of statements
   *
   * @exception  java.sql.SQLException if an error occurs
   *
  **/
  public void setMaxStatements(int parm) throws SQLException
  {
    try {
      Field fld = getClass().getField(this.n_maxStatements);
      setField(fld, parm);
    } catch (Exception e) {
      throw new VirtuosoException("Error: "+e.toString(), VirtuosoException.OK);
    }
  }


  private void setField(Field fld, int parm) throws Exception {
    if (propertyCycle == 0)
      fld.setInt(this, parm);
    else
      synchronized(propQueue) {
        propQueue.add(new NewProperty(fld, parm));
        propEnforceTime = ((NewProperty)propQueue.first()).enforceTime;
      }
  }

  private void check_close()  throws SQLException
  {
    if (isClosed)
      throw new VirtuosoException("ConnectionPoolDataSource is closed", VirtuosoException.OK);
  }


  ///////////////// Inner classes //////////////////////
  private class NewProperty {
    protected long enforceTime;
    protected Field fld;
    protected int arg;

    protected NewProperty(Field _fld, int _arg) {
      fld = _fld;
      arg = _arg;
      enforceTime = System.currentTimeMillis() + propertyCycle * 1000L;
    }
  }


  private class OpenHelper extends Thread {

    private String conn_url;
    private Properties info;
    private String connKey;
    private int count;

    protected OpenHelper(int _count, Properties _info) {
      count = _count;
      info = _info;

      conn_url = create_url();
      connKey = create_url_key(conn_url, info);
      setName("Virtuoso OpenHelper");
    }

    public void run() {
      if (connPool.cacheSize >= count || (maxPoolSize != 0 && connPool.cacheSize >= maxPoolSize))
        return;

      for(int i = 0; i < count; i++)
        try {

          VirtuosoConnection conn = new VirtuosoConnection (conn_url, "localhost", 1111, info);
          connPool.addPooledConnection(new VirtuosoPooledConnection(conn, connKey));
          if ((minPoolSize != 0 && connPool.cacheSize >= minPoolSize) 
              || (maxPoolSize != 0 && connPool.cacheSize >= maxPoolSize))
            return;
        } catch (Exception e) {
        }
    }

  }


  private class CloseHelper extends Thread {

    private LinkedList connList;
    private PooledConnection pconn;

    private CloseHelper() {
      setName("Virtuoso CloseHelper");
    }

    protected CloseHelper(LinkedList _connList) {
      this();
      connList = _connList;
    }

    protected CloseHelper(PooledConnection _pconn) {
      this();
      pconn = _pconn;
    }

    public void run() {
      if (connList != null) {
        for(ListIterator i = connList.listIterator(); i.hasNext(); )
          try {
            ((VirtuosoPooledConnection)i.next()).close();
          } catch (Exception e) { }
        connList.clear();
      } else {
        try {
          pconn.close();
        } catch (Exception e) {
        }
      }
    }

  }


  private class ConnCache {

#if JDK_VER >= 16
    private LinkedList<Object>  unUsed = new LinkedList<Object>();
    private HashMap<Object,Object> in_Use = new HashMap<Object,Object>(32);
#else
    private LinkedList  unUsed = new LinkedList();
    private HashMap in_Use = new HashMap(32);
#endif
    private int cacheSize = 0;

    private VirtuosoConnectionPoolDataSource cpds;

    private ConnCache(VirtuosoConnectionPoolDataSource _cpds) {
      cpds = _cpds;
    }

    //add a new connection to pool
    private void addPooledConnection(VirtuosoPooledConnection pconn) {
      synchronized(this) {
        connPool.unUsed.addLast(pconn);
        connPool.cacheSize++;
        notifyAll();
      }
    }

    //close all connections & clear the pool
    private void clear() throws SQLException {
      VirtuosoPooledConnection pconn;

      synchronized (this) {
        for(Iterator iterator = in_Use.keySet().iterator(); iterator.hasNext(); ) {
          pconn = (VirtuosoPooledConnection)iterator.next();
          pconn.removeConnectionEventListener(cpds);
          cacheSize--;
          try {
            pconn.close();
          } catch (Exception e) {}
        }
        in_Use.clear();

        for(Iterator iterator = unUsed.iterator(); iterator.hasNext(); ) {
          pconn = (VirtuosoPooledConnection)iterator.next();
          cacheSize--;
          try {
            pconn.close();
          } catch (Exception e) {}
        }
        unUsed.clear();
      }
    }


    private void reusePooledConnection(VirtuosoPooledConnection pconn) throws SQLException {

      if (pconn == null)
        return;

      //reuse Connection
      boolean reUsed = true;
      pconn.removeConnectionEventListener(cpds);

      synchronized(this) {
        VirtuosoPooledConnection pooledConn = null;
        if ((pooledConn = (VirtuosoPooledConnection)in_Use.remove(pconn)) == null) {
          throw new VirtuosoException("Unexpected state of cache", VirtuosoException.OK);
        }

        if (maxPoolSize != 0  &&  cacheSize > maxPoolSize) {
          // close connection
          cacheSize--;
          reUsed = false;
        } else {
          // reUse connection & put connection to the unUsed pool
          pooledConn = pconn.reuse();
          unUsed.addFirst(pooledConn);
          notifyAll();
        }
      }

      if ( !reUsed) {
//      System.out.println("close pconn....");
        CloseHelper helpThread = new CloseHelper(pconn);
        helpThread.start();
      }
    }


    private void closePooledConnection(VirtuosoPooledConnection pconn) throws SQLException {
//    System.out.println("Calling closePooledConnection");
      pconn.removeConnectionEventListener(cpds);

      synchronized(this) {
        VirtuosoPooledConnection pooledConn;
        if ((pooledConn = (VirtuosoPooledConnection)in_Use.remove(pconn)) == null)
          throw new VirtuosoException("Unexpected state of cache", VirtuosoException.OK);
        cacheSize--;
      }

      pconn.close();
    }

    private VirtuosoPooledConnection lookup(String _Key) {
#if JDK_VER >= 16
      LinkedList<Object> closeTmp = new LinkedList<Object>();
#else
      LinkedList closeTmp = new LinkedList();
#endif
      VirtuosoPooledConnection pooledConn;
      int _hashKey = _Key.hashCode();

      try {
        for(ListIterator iterator = unUsed.listIterator(); iterator.hasNext(); ) {
          pooledConn = (VirtuosoPooledConnection)iterator.next();
          if (pooledConn.hashConnURL == _hashKey && pooledConn.connURL.equals(_Key)) {
            iterator.remove();
	    if (pooledConn.isConnectionLost()) {
	      synchronized(this) {              
                if (cacheSize > 1) 
                  --cacheSize;
                closeTmp.add(pooledConn);
              }
	    } else {
              return pooledConn;
	    }
          }
        }

        return null;

      } finally {
        if (closeTmp.size() > 0) {
          // close connections
          CloseHelper helpThread = new CloseHelper(closeTmp);
          helpThread.start();
        }
      }
    }


    // get connection from cache or create a new connection
    private PooledConnection getPooledConnection(Properties info,
                                                 String connKey,
                                                 String conn_url)
        throws java.sql.SQLException
    {
      VirtuosoPooledConnection pconn = null;
      VirtuosoConnection conn;

    //try to find an unused Connection
      synchronized(this) {
        if (!unUsed.isEmpty() && (pconn = lookup(connKey)) != null) {
          pconn.init(cpds);
          in_Use.put(pconn, pconn);
          return pconn;
        }
      }
    // if couldn't found an unused Connection
      synchronized(this) { 
        if (maxPoolSize == 0 || cacheSize < maxPoolSize) {
         // establish a new Connection
          conn = new VirtuosoConnection (conn_url, "localhost", 1111, info);
          cacheSize++;
          pconn = new VirtuosoPooledConnection(conn, connKey, cpds);
          in_Use.put(pconn, pconn);
          return pconn;
        }

      } 

      // wait a free Connection
      long start = System.currentTimeMillis();
      long _timeout = loginTimeout * 1000L;
      Thread thr = Thread.currentThread();
      while (pconn == null) {
//    System.out.println("Thread "+thr+" begin a waiting...");
        synchronized(this) {
          if (!unUsed.isEmpty() && (pconn = lookup(connKey)) != null) {
//          System.out.println("Thread "+thr+" has found a free connection");
            pconn.init(cpds);
            in_Use.put(pconn, pconn);
            return pconn;
          }

          try {
            if (loginTimeout > 0) {
              wait(_timeout);
              _timeout -= (System.currentTimeMillis() - start);
              if (_timeout < 0) {
//              System.out.println("Thread "+thr+" : loginTimeout has expired");
                throw new VirtuosoException("Connection failed loginTimeout has expired", VirtuosoException.TIMEOUT);
              }
            } else {
              wait();
            }
//          System.out.println("Thread "+thr+" has woken ");
          } catch (InterruptedException e) {
          }
        }
      }

      return null;
    }


    private void checkPool() {
      VirtuosoPooledConnection pooledConn;
#if JDK_VER >= 16
      LinkedList<Object> closeTmp = new LinkedList<Object>();
#else
      LinkedList closeTmp = new LinkedList();
#endif
      ListIterator l_iter;

      if (maxIdleTime != 0) {
       // remove a long time unused connections
        long minTime = System.currentTimeMillis() - maxIdleTime * 1000L;

        synchronized(this) {
          for(l_iter = unUsed.listIterator(); l_iter.hasNext(); ) {
            pooledConn = (VirtuosoPooledConnection)l_iter.next();
            if (pooledConn.tmClosed < minTime) {
               closeTmp.add(pooledConn);
               l_iter.remove();
               cacheSize--;
            }
          }
        }
      }

      synchronized(this) {
        if (maxPoolSize != 0 && cacheSize > maxPoolSize) {
         //remove connections
          int count = cacheSize - maxPoolSize;
          for(l_iter = unUsed.listIterator(); l_iter.hasNext() && count > 0; count--) {
            closeTmp.add(l_iter.next());
            l_iter.remove();
            cacheSize--;
          }
        }
      }

      if (closeTmp != null && closeTmp.size() > 0) {
       // close connections
        CloseHelper helpThread = new CloseHelper(closeTmp);
        helpThread.start();
      }

      synchronized(this) {
        if (minPoolSize != 0 && cacheSize < minPoolSize) {
         //add connections
          Properties info = createConnProperties();
          int count = minPoolSize - cacheSize;
          OpenHelper helpThread = new OpenHelper(count, info);
          helpThread.start();
        }
      }
    }

  }

}