Example usage for java.util.concurrent.locks ReentrantLock ReentrantLock

List of usage examples for java.util.concurrent.locks ReentrantLock ReentrantLock

Introduction

In this page you can find the example usage for java.util.concurrent.locks ReentrantLock ReentrantLock.

Prototype

public ReentrantLock() 

Source Link

Document

Creates an instance of ReentrantLock .

Usage

From source file:edu.usu.sdl.openstorefront.service.ComponentServiceImpl.java

@Override
public void processComponentUpdates() {
    ReentrantLock lock = new ReentrantLock();
    lock.lock();//from w  w w .j a va 2  s  . c  om
    try {
        ComponentUpdateQueue updateQueueExample = new ComponentUpdateQueue();
        updateQueueExample.setNodeId(PropertiesManager.getNodeName());

        List<ComponentUpdateQueue> componentUpdateQueues = persistenceService
                .queryByExample(ComponentUpdateQueue.class, updateQueueExample);
        if (componentUpdateQueues.isEmpty() == false) {
            //Get the latest entries
            Map<String, ComponentUpdateQueue> componentMap = new HashMap<>();
            for (ComponentUpdateQueue updateQueue : componentUpdateQueues) {
                if (componentMap.containsKey(updateQueue.getUpdateId())) {
                    ComponentUpdateQueue existing = componentMap.get(updateQueue.getUpdateId());
                    if (existing.getUpdateDts().before(updateQueue.getUpdateDts())) {
                        componentMap.put(updateQueue.getUpdateId(), updateQueue);
                    }
                } else {
                    componentMap.put(updateQueue.getUpdateId(), updateQueue);
                }
            }

            List<Component> componentsToIndex = new ArrayList<>();
            for (ComponentUpdateQueue componentUpdate : componentMap.values()) {
                String componentId = componentUpdate.getComponentId();

                Component component = persistenceService.findById(Component.class, componentId);
                if (component != null) {
                    component.setLastActivityDts(componentUpdate.getUpdateDts());
                    persistenceService.persist(component);
                    getUserService().checkComponentWatches(component);
                    componentsToIndex.add(component);
                } else {
                    log.log(Level.FINE,
                            "Component not found to update last Activity. Component may have been removed.",
                            "Check component Id: " + componentId);
                }
            }
            getSearchService().indexComponents(componentsToIndex);

            //remove processed records
            for (ComponentUpdateQueue updateQueue : componentUpdateQueues) {
                ComponentUpdateQueue componentUpdateQueue = persistenceService
                        .findById(ComponentUpdateQueue.class, updateQueue.getUpdateId());
                if (componentUpdateQueue != null) {
                    persistenceService.delete(componentUpdateQueue);
                }
            }
        }
    } finally {
        lock.unlock();
    }

}

From source file:lcmc.gui.resources.ServiceInfo.java

/** Returns existing service manu item. */
private MyMenu getExistingServiceMenuItem(final String name, final boolean enableForNew,
        final boolean testOnly) {
    final ServiceInfo thisClass = this;
    return new MyMenu(name, new AccessMode(ConfigData.AccessType.ADMIN, false),
            new AccessMode(ConfigData.AccessType.OP, false)) {
        private static final long serialVersionUID = 1L;
        private final Lock mUpdateLock = new ReentrantLock();

        @Override/*from w  ww  .j  a v a 2  s .  com*/
        public String enablePredicate() {
            if (getBrowser().clStatusFailed()) {
                return ClusterBrowser.UNKNOWN_CLUSTER_STATUS_STRING;
            } else if (getService().isRemoved()) {
                return IS_BEING_REMOVED_STRING;
            } else if (getService().isOrphaned()) {
                return IS_ORPHANED_STRING;
            } else if (!enableForNew && getService().isNew()) {
                return IS_NEW_STRING;
            }
            if (getBrowser().getExistingServiceList(thisClass).size() == 0) {
                return "&lt;&lt;empty;&gt;&gt;";
            }
            return null;
        }

        @Override
        public void update() {
            final Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    if (mUpdateLock.tryLock()) {
                        try {
                            updateThread();
                        } finally {
                            mUpdateLock.unlock();
                        }
                    }
                }
            });
            t.start();
        }

        private void updateThread() {
            final JCheckBox colocationWi = new JCheckBox("Colo", true);
            final JCheckBox orderWi = new JCheckBox("Order", true);
            colocationWi.setBackground(ClusterBrowser.STATUS_BACKGROUND);
            colocationWi.setPreferredSize(colocationWi.getMinimumSize());
            orderWi.setBackground(ClusterBrowser.STATUS_BACKGROUND);
            orderWi.setPreferredSize(orderWi.getMinimumSize());
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    setEnabled(false);
                }
            });
            Tools.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    removeAll();
                }
            });

            final MyListModel<MyMenuItem> dlm = new MyListModel<MyMenuItem>();
            final Map<MyMenuItem, ButtonCallback> callbackHash = new HashMap<MyMenuItem, ButtonCallback>();
            final MyList<MyMenuItem> list = new MyList<MyMenuItem>(dlm, getBackground());

            final List<JDialog> popups = new ArrayList<JDialog>();
            for (final ServiceInfo asi : getBrowser().getExistingServiceList(thisClass)) {
                if (asi.isConstraintPH() && isConstraintPH()) {
                    continue;
                }
                if (asi.getCloneInfo() != null || asi.getGroupInfo() != null) {
                    /* skip services that are clones or in groups. */
                    continue;
                }
                addExistingServiceMenuItem(asi.toString(), asi, dlm, callbackHash, list, colocationWi, orderWi,
                        popups, testOnly);
                asi.addExistingGroupServiceMenuItems(thisClass, dlm, callbackHash, list, colocationWi, orderWi,
                        popups, testOnly);
            }
            final JPanel colOrdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
            colOrdPanel.setBackground(ClusterBrowser.STATUS_BACKGROUND);
            colOrdPanel.add(colocationWi);
            colOrdPanel.add(orderWi);
            final MyMenu thisM = this;
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    @Override
                    public void run() {
                        final boolean ret = Tools.getScrollingMenu(name, colOrdPanel, thisM, dlm, list,
                                thisClass, popups, callbackHash);
                        if (!ret) {
                            setEnabled(false);
                        }
                    }
                });
            } catch (final InterruptedException ix) {
                Thread.currentThread().interrupt();
            } catch (final InvocationTargetException x) {
                Tools.printStackTrace();
            }
            super.update();
        }
    };
}

From source file:lcmc.gui.resources.ServiceInfo.java

/** Adds new Service and dependence. */
private MyMenu getAddServiceMenuItem(final boolean testOnly, final String name) {
    final ServiceInfo thisClass = this;
    return new MyMenu(name, new AccessMode(ConfigData.AccessType.ADMIN, false),
            new AccessMode(ConfigData.AccessType.OP, false)) {
        private static final long serialVersionUID = 1L;
        private final Lock mUpdateLock = new ReentrantLock();

        @Override//from w w  w . j  a va  2 s . com
        public String enablePredicate() {
            if (getBrowser().clStatusFailed()) {
                return ClusterBrowser.UNKNOWN_CLUSTER_STATUS_STRING;
            } else if (getService().isRemoved()) {
                return IS_BEING_REMOVED_STRING;
            } else if (getService().isOrphaned()) {
                return IS_ORPHANED_STRING;
            } else if (getService().isNew()) {
                return IS_NEW_STRING;
            }
            return null;
        }

        @Override
        public void update() {
            final Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    if (mUpdateLock.tryLock()) {
                        try {
                            updateThread();
                        } finally {
                            mUpdateLock.unlock();
                        }
                    }
                }
            });
            t.start();
        }

        private void updateThread() {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    setEnabled(false);
                }
            });
            Tools.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    removeAll();
                }
            });
            final Point2D pos = getPos();
            final CRMXML crmXML = getBrowser().getCRMXML();
            final ResourceAgent fsService = crmXML.getResourceAgent("Filesystem",
                    ResourceAgent.HEARTBEAT_PROVIDER, ResourceAgent.OCF_CLASS);
            final MyMenu thisMenu = this;
            if (crmXML.isLinbitDrbdPresent()) { /* just skip it, if it
                                                   is not */
                final ResourceAgent linbitDrbdService = crmXML.getHbLinbitDrbd();
                /* Linbit:DRBD */
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            addDrbdLinbitMenu(thisMenu, crmXML, pos, fsService, testOnly);
                        }
                    });
                } catch (final InterruptedException ix) {
                    Thread.currentThread().interrupt();
                } catch (final InvocationTargetException x) {
                    Tools.printStackTrace();
                }

            }
            if (crmXML.isDrbddiskPresent()) { /* just skip it,
                                                 if it is not */
                /* drbddisk */
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            addDrbddiskMenu(thisMenu, crmXML, pos, fsService, testOnly);
                        }
                    });
                } catch (final InterruptedException ix) {
                    Thread.currentThread().interrupt();
                } catch (final InvocationTargetException x) {
                    Tools.printStackTrace();
                }
            }
            final ResourceAgent ipService = crmXML.getResourceAgent("IPaddr2", ResourceAgent.HEARTBEAT_PROVIDER,
                    ResourceAgent.OCF_CLASS);
            if (ipService != null) { /* just skip it, if it is not*/
                /* ipaddr */
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            addIpMenu(thisMenu, pos, ipService, testOnly);
                        }
                    });
                } catch (final InterruptedException ix) {
                    Thread.currentThread().interrupt();
                } catch (final InvocationTargetException x) {
                    Tools.printStackTrace();
                }
            }
            if (fsService != null) { /* just skip it, if it is not*/
                /* Filesystem */
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            addFilesystemMenu(thisMenu, pos, fsService, testOnly);
                        }
                    });
                } catch (final InterruptedException ix) {
                    Thread.currentThread().interrupt();
                } catch (final InvocationTargetException x) {
                    Tools.printStackTrace();
                }
            }
            final List<JDialog> popups = new ArrayList<JDialog>();
            for (final String cl : ClusterBrowser.HB_CLASSES) {
                final List<ResourceAgent> services = getAddServiceList(cl);
                if (services.size() == 0) {
                    /* no services, don't show */
                    continue;
                }
                final JCheckBox colocationWi = new JCheckBox("Colo", true);
                final JCheckBox orderWi = new JCheckBox("Order", true);
                colocationWi.setBackground(ClusterBrowser.STATUS_BACKGROUND);
                colocationWi.setPreferredSize(colocationWi.getMinimumSize());
                orderWi.setBackground(ClusterBrowser.STATUS_BACKGROUND);
                orderWi.setPreferredSize(orderWi.getMinimumSize());
                final JPanel colOrdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
                colOrdPanel.setBackground(ClusterBrowser.STATUS_BACKGROUND);
                colOrdPanel.add(colocationWi);
                colOrdPanel.add(orderWi);
                boolean mode = !AccessMode.ADVANCED;
                if (ResourceAgent.UPSTART_CLASS.equals(cl) || ResourceAgent.SYSTEMD_CLASS.equals(cl)) {
                    mode = AccessMode.ADVANCED;
                }
                if (ResourceAgent.LSB_CLASS.equals(cl)
                        && !getAddServiceList(ResourceAgent.SERVICE_CLASS).isEmpty()) {
                    mode = AccessMode.ADVANCED;
                }
                final MyMenu classItem = new MyMenu(ClusterBrowser.getClassMenu(cl),
                        new AccessMode(ConfigData.AccessType.ADMIN, mode),
                        new AccessMode(ConfigData.AccessType.OP, mode));
                final MyListModel<MyMenuItem> dlm = new MyListModel<MyMenuItem>();
                for (final ResourceAgent ra : services) {
                    try {
                        SwingUtilities.invokeAndWait(new Runnable() {
                            @Override
                            public void run() {
                                addResourceAgentMenu(ra, dlm, pos, popups, colocationWi, orderWi, testOnly);
                            }
                        });
                    } catch (final InterruptedException ix) {
                        Thread.currentThread().interrupt();
                    } catch (final InvocationTargetException x) {
                        Tools.printStackTrace();
                    }
                }
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            final boolean ret = Tools.getScrollingMenu(ClusterBrowser.getClassMenu(cl),
                                    colOrdPanel, classItem, dlm, new MyList<MyMenuItem>(dlm, getBackground()),
                                    thisClass, popups, null);
                            if (!ret) {
                                classItem.setEnabled(false);
                            }
                            thisMenu.add(classItem);
                        }
                    });
                } catch (final InterruptedException ix) {
                    Thread.currentThread().interrupt();
                } catch (final InvocationTargetException x) {
                    Tools.printStackTrace();
                }
            }
            super.update();
        }
    };
}

From source file:org.apache.hadoop.hive.metastore.HiveMetaStore.java

/**
 * @param args//from   www  .ja v a  2 s .  co  m
 */
public static void main(String[] args) throws Throwable {
    HiveConf.setLoadMetastoreConfig(true);
    final HiveConf conf = new HiveConf(HMSHandler.class);

    HiveMetastoreCli cli = new HiveMetastoreCli(conf);
    cli.parse(args);
    final boolean isCliVerbose = cli.isVerbose();
    // NOTE: It is critical to do this prior to initializing log4j, otherwise
    // any log specific settings via hiveconf will be ignored
    Properties hiveconf = cli.addHiveconfToSystemProperties();

    // If the log4j.configuration property hasn't already been explicitly set,
    // use Hive's default log4j configuration
    if (System.getProperty("log4j.configurationFile") == null) {
        // NOTE: It is critical to do this here so that log4j is reinitialized
        // before any of the other core hive classes are loaded
        try {
            LogUtils.initHiveLog4j();
        } catch (LogInitializationException e) {
            HMSHandler.LOG.warn(e.getMessage());
        }
    }
    HiveStringUtils.startupShutdownMessage(HiveMetaStore.class, args, LOG);

    try {
        String msg = "Starting hive metastore on port " + cli.port;
        HMSHandler.LOG.info(msg);
        if (cli.isVerbose()) {
            System.err.println(msg);
        }

        // set all properties specified on the command line
        for (Map.Entry<Object, Object> item : hiveconf.entrySet()) {
            conf.set((String) item.getKey(), (String) item.getValue());
        }

        // Add shutdown hook.
        ShutdownHookManager.addShutdownHook(new Runnable() {
            @Override
            public void run() {
                String shutdownMsg = "Shutting down hive metastore.";
                HMSHandler.LOG.info(shutdownMsg);
                if (isCliVerbose) {
                    System.err.println(shutdownMsg);
                }
                if (conf.getBoolVar(ConfVars.METASTORE_METRICS)) {
                    try {
                        MetricsFactory.close();
                    } catch (Exception e) {
                        LOG.error("error in Metrics deinit: " + e.getClass().getName() + " " + e.getMessage(),
                                e);
                    }
                }
            }
        });

        //Start Metrics for Standalone (Remote) Mode
        if (conf.getBoolVar(ConfVars.METASTORE_METRICS)) {
            try {
                MetricsFactory.init(conf);
            } catch (Exception e) {
                // log exception, but ignore inability to start
                LOG.error("error in Metrics init: " + e.getClass().getName() + " " + e.getMessage(), e);
            }
        }

        Lock startLock = new ReentrantLock();
        Condition startCondition = startLock.newCondition();
        AtomicBoolean startedServing = new AtomicBoolean();
        startMetaStoreThreads(conf, startLock, startCondition, startedServing);
        startMetaStore(cli.getPort(), ShimLoader.getHadoopThriftAuthBridge(), conf, startLock, startCondition,
                startedServing);
    } catch (Throwable t) {
        // Catch the exception, log it and rethrow it.
        HMSHandler.LOG.error("Metastore Thrift Server threw an exception...", t);
        throw t;
    }
}