KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > activemq > transport > discovery > rendezvous > JmDNSFactory


1 /**
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one or more
4  * contributor license agreements. See the NOTICE file distributed with
5  * this work for additional information regarding copyright ownership.
6  * The ASF licenses this file to You under the Apache License, Version 2.0
7  * (the "License"); you may not use this file except in compliance with
8  * the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18 package org.apache.activemq.transport.discovery.rendezvous;
19
20 import java.io.IOException JavaDoc;
21 import java.net.InetAddress JavaDoc;
22 import java.util.HashMap JavaDoc;
23 import java.util.Map JavaDoc;
24 import javax.jmdns.JmDNS;
25 import java.util.concurrent.atomic.AtomicInteger JavaDoc;
26
27 public class JmDNSFactory {
28     
29     static Map JavaDoc registry = new HashMap JavaDoc();
30     static class UsageTracker {
31         AtomicInteger JavaDoc count = new AtomicInteger JavaDoc(0);
32         JmDNS jmDNS;
33     }
34     
35     static synchronized JmDNS create(final InetAddress JavaDoc address) throws IOException JavaDoc {
36         UsageTracker tracker = (UsageTracker)registry.get(address);
37         if( tracker == null ) {
38             tracker = new UsageTracker();
39             tracker.jmDNS = new JmDNS(address) {
40                 public void close() {
41                     if( onClose(address) ) {
42                         super.close();
43                     }
44                 }
45             };
46             registry.put(address, tracker);
47         }
48         tracker.count.incrementAndGet();
49         return tracker.jmDNS;
50     }
51     
52     static synchronized boolean onClose(InetAddress JavaDoc address){
53         UsageTracker tracker=(UsageTracker) registry.get(address);
54         if(tracker!=null){
55             if(tracker.count.decrementAndGet()==0){
56                 registry.remove(address);
57                 return true;
58             }
59         }
60         return false;
61     }
62 }
63
Popular Tags