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:com.chinamobile.bcbsp.comm.MessageQueuesForDisk.java

/**
 * Constructor.//w  w w.  j a  va2s.c o m
 * @param job
 * @param partitionID
 */
public MessageQueuesForDisk(BSPJob job, int partitionID) {
    LOG.info("========== Initializing Message Queues Data For Disk ==========");
    this.dataPercent = job.getMemoryDataPercent(); // Default 0.8
    this.jobID = job.getJobID();
    this.partitionID = partitionID;
    // ratio of graph data
    this.beta = job.getBeta();
    this.hashBucketNumber = job.getHashBucketNumber();
    LOG.info("[beta] = " + this.beta);
    LOG.info("[hashBucketNumber] = " + this.hashBucketNumber);
    // the structure of three kinds message queues
    this.outgoingQueues = new ConcurrentHashMap<String, ConcurrentLinkedQueue<IMessage>>();
    this.incomingQueues = new ArrayList<BucketMeta>(this.hashBucketNumber);
    this.incomedQueues = new ArrayList<BucketMeta>(this.hashBucketNumber);
    for (int i = 0; i < this.hashBucketNumber; i++) {
        BucketMeta meta = new BucketMeta();
        meta.onDiskFlag = false;
        meta.length = 0;
        meta.lengthInMemory = 0;
        meta.count = 0;
        meta.countInMemory = 0;
        meta.queueMap = new ConcurrentHashMap<String, ConcurrentLinkedQueue<IMessage>>();
        this.incomingQueues.add(meta);
        meta = new BucketMeta();
        meta.onDiskFlag = false;
        meta.length = 0;
        meta.lengthInMemory = 0;
        meta.count = 0;
        meta.countInMemory = 0;
        meta.queueMap = new ConcurrentHashMap<String, ConcurrentLinkedQueue<IMessage>>();
        this.incomedQueues.add(meta);
    }
    // Initialize the bucket file locks
    this.incomedFileLocks = new ReentrantLock[this.hashBucketNumber];
    this.incomingFileLocks = new ReentrantLock[this.hashBucketNumber];
    for (int i = 0; i < this.hashBucketNumber; i++) {
        this.incomedFileLocks[i] = new ReentrantLock();
        this.incomingFileLocks[i] = new ReentrantLock();
    }
    // Initialize the size of objects.
    BSPConfiguration conf = new BSPConfiguration();
    if (conf.getInt(Constants.BC_BSP_JVM_VERSION, 32) == 64) {
        sizer = ObjectSizer.forSun64BitsVM();
    } else {
        sizer = ObjectSizer.forSun32BitsVM();
    }
    this.sizeOfRef = sizer.sizeOfRef();
    this.sizeOfInteger = sizer.sizeOf(new Integer(0));
    this.sizeOfChar = sizer.sizeOfChar();
    this.sizeOfEmptyMessageQueue = sizer.sizeOf(new ConcurrentLinkedQueue<IMessage>());
    // Size will be evaluted later based on first m received messages.
    this.sizeOfMessage = MESSAGE_SIZE; // Default
    // Get the memory mxBean.
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    // Get the heap memory usage.
    MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
    long maxHeapSize = memoryUsage.getMax();
    LOG.info("[JVM max Heap size] = " + maxHeapSize / MB_SIZE + "MB");
    this.sizeOfMessagesSpace = (long) (maxHeapSize * dataPercent * (1.0f - beta));
    this.sizeThreshold = (long) (sizeOfMessagesSpace);
    this.countThreshold = (long) (sizeThreshold / sizeOfMessage);
    this.countThresholdForBucket = this.countThreshold / (3 * this.hashBucketNumber);
    LOG.info("[size of Messages Space Threshold] = " + this.sizeThreshold / MB_SIZE + "MB");
    LOG.info("[count of Messages In Memory Threshold] = " + this.countThreshold / KB_SIZE + "K");
    this.sizeOfMessagesDataInMem = 0;
    this.countOfMessagesDataInMem = 0;
    this.totalSizeOfMessages = 0;
    this.totalCount = 0;
    this.sizeOfHashMapsInMem = 0;
    this.fileRoot = new File("/tmp/bcbsp/" + this.jobID.toString() + "/" + "partition-" + this.partitionID);
    this.messagesDataFile = new File(this.fileRoot + "/" + "MessagesData");
    // If the root dir does not exit, create it.
    if (!this.fileRoot.exists()) {
        this.fileRoot.mkdirs();
    }
    // If the messages data dir does not exit, create it.
    if (!this.messagesDataFile.exists()) {
        this.messagesDataFile.mkdir();
    }
    // Initialize the current accessed bucket index.
    this.currentBucket = -1;
    LOG.info("===============================================================");
}

From source file:org.proninyaroslav.libretorrent.fragments.MainFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (activity == null) {
        activity = (AppCompatActivity) getActivity();
    }/*  www .  jav a  2s  .  c  o  m*/

    showBlankFragment();

    sync = new ReentrantLock();

    toolbar = (Toolbar) activity.findViewById(R.id.toolbar);

    if (toolbar != null) {
        toolbar.setTitle(R.string.app_name);
    }

    View spinnerContainer = LayoutInflater.from(activity).inflate(R.layout.toolbar_spinner, toolbar, false);
    ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT);
    toolbar.addView(spinnerContainer, lp);

    spinnerAdapter = new ToolbarSpinnerAdapter(activity);
    spinnerAdapter.addItems(getSpinnerList());

    spinner = (Spinner) spinnerContainer.findViewById(R.id.toolbar_spinner);
    spinner.setAdapter(spinnerAdapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            setTorrentListFilter(spinnerAdapter.getItem(i));
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
            /* Nothing */
        }
    });

    activity.setSupportActionBar(toolbar);
    setHasOptionsMenu(true);

    addTorrentButton = (FloatingActionMenu) activity.findViewById(R.id.add_torrent_button);
    addTorrentButton.setClosedOnTouchOutside(true);

    openFileButton = (FloatingActionButton) activity.findViewById(R.id.open_file_button);
    openFileButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            addTorrentButton.close(true);
            torrentFileChooserDialog();
        }
    });

    addLinkButton = (FloatingActionButton) activity.findViewById(R.id.add_link_button);
    addLinkButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            addTorrentButton.close(true);
            addLinkDialog();
        }
    });

    if (savedInstanceState != null) {
        prevImplIntent = savedInstanceState.getParcelable(TAG_PREV_IMPL_INTENT);
    }

    activity.bindService(new Intent(activity.getApplicationContext(), TorrentTaskService.class), connection,
            Context.BIND_AUTO_CREATE);

    torrentsList = (EmptyRecyclerView) activity.findViewById(R.id.torrent_list);
    layoutManager = new LinearLayoutManager(activity);
    torrentsList.setLayoutManager(layoutManager);

    /*
     * A RecyclerView by default creates another copy of the ViewHolder in order to
     * fade the views into each other. This causes the problem because the old ViewHolder gets
     * the payload but then the new one doesn't. So needs to explicitly tell it to reuse the old one.
     */
    DefaultItemAnimator animator = new DefaultItemAnimator() {
        @Override
        public boolean canReuseUpdatedViewHolder(RecyclerView.ViewHolder viewHolder) {
            return true;
        }
    };
    torrentsList.setItemAnimator(animator);
    torrentsList.addItemDecoration(new RecyclerViewDividerDecoration(activity.getApplicationContext(),
            R.drawable.torrent_list_divider));
    torrentsList.setEmptyView(activity.findViewById(R.id.empty_view_torrent_list));

    adapter = new TorrentListAdapter(new ArrayList<TorrentStateParcel>(), activity, R.layout.item_torrent_list,
            this);

    setTorrentListFilter((String) spinner.getSelectedItem());

    torrentsList.setAdapter(adapter);

    Intent i = activity.getIntent();
    /* If add torrent dialog has been called by an implicit intent */
    if (i != null && i.hasExtra(AddTorrentActivity.TAG_RESULT_TORRENT)) {
        if (prevImplIntent == null || !prevImplIntent.equals(i)) {
            prevImplIntent = i;
            Torrent torrent = i.getParcelableExtra(AddTorrentActivity.TAG_RESULT_TORRENT);

            if (torrent != null) {
                ArrayList<Torrent> list = new ArrayList<>();
                list.add(torrent);
                addTorrentsRequest(list);
            }
        }

    } else if (i != null && i.getAction() != null) {
        switch (i.getAction()) {
        case NotificationReceiver.NOTIFY_ACTION_ADD_TORRENT:
            addTorrentMenu = true;
            /* Prevents re-reading action after device configuration changes */
            i.setAction(null);
            break;
        }
    }

    /* Show add torrent menu (called from service) after window is displayed */
    activity.getWindow().findViewById(android.R.id.content).post(new Runnable() {
        @Override
        public void run() {
            if (addTorrentMenu) {
                /* Hide notification bar */
                activity.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
                addTorrentMenu = false;

                View v = activity.getWindow().findViewById(android.R.id.content);
                registerForContextMenu(v);
                activity.openContextMenu(v);
                unregisterForContextMenu(v);
            }
        }
    });

    if (savedInstanceState != null) {
        selectedTorrents = savedInstanceState.getStringArrayList(TAG_SELECTED_TORRENTS);
        if (savedInstanceState.getBoolean(TAG_IN_ACTION_MODE, false)) {
            actionMode = activity.startActionMode(actionModeCallback);
            adapter.setSelectedItems(savedInstanceState.getIntegerArrayList(TAG_SELECTABLE_ADAPTER));
            actionMode.setTitle(String.valueOf(adapter.getSelectedItemCount()));
        }
    }
}

From source file:uk.ac.diamond.scisoft.ncd.passerelle.actors.NcdProcessingModel.java

public NcdProcessingModel() {
     super();/*from w  w  w .j a v a 2  s  . c o m*/

     lock = new ReentrantLock();

     normChannel = -1;
     bgScaling = 1.0;
     bgFile = "";
     drFile = "";
     calibration = "";
     bgDetector = "";
     intSector = new SectorROI();
     slope = null;
     intercept = null;
     cameraLength = null;
     energy = null;
     mask = new BooleanDataset();
     drData = new FloatDataset();
     firstFrame = null;
     lastFrame = null;
     frameSelection = null;

     crb = new CalibrationResultsBean();

     flags = new NcdReductionFlags();
     absScaling = 1.0;

     gridAverage = null;
     bgGridAverage = null;
     enableBgAverage = false;

 }

From source file:org.wso2.carbon.mediation.initializer.ServiceBusInitializer.java

protected void activate(ComponentContext ctxt) {

    log.info("Starting ESB...");

    // FIXME: this is a hack to get rid of the https port retrieval from the axis2
    // configuration returning the non blocking https transport. Ideally we should be able
    // to fix this by making it possible to let the authentication of carbon be done through
    // the non blocking https transport
    setHttpsProtForConsole();//w w w  .j  a  va 2 s .co  m

    //clean up temp folder created for connector class loader reference
    String javaTempDir = System.getProperty("java.io.tmpdir");
    String APP_UNZIP_DIR = javaTempDir.endsWith(File.separator) ? javaTempDir + "libs"
            : javaTempDir + File.separator + "libs";
    cleanupTempDirectory(APP_UNZIP_DIR);

    try {
        BundleContext bndCtx = ctxt.getBundleContext();
        ConfigurationHolder.getInstance().setBundleContext(bndCtx);

        TenantServiceBusInitializer listener = new TenantServiceBusInitializer();
        bndCtx.registerService(Axis2ConfigurationContextObserver.class.getName(), listener, null);
        // initialize the lock
        Lock lock = new ReentrantLock();
        configCtxSvc.getServerConfigContext().getAxisConfiguration()
                .addParameter(ServiceBusConstants.SYNAPSE_CONFIG_LOCK, lock);

        // first check which configuration should be active
        UserRegistry registry = registryService.getConfigSystemRegistry();

        // init the multiple configuration tracker
        ConfigurationManager configurationManager = new ConfigurationManager(registry,
                configCtxSvc.getServerConfigContext());
        configurationManager.init();

        // set the event broker as a property
        if (eventBroker != null) {
            configCtxSvc.getServerConfigContext().setProperty("mediation.event.broker", eventBroker);
        }

        // Initialize Synapse
        ServerContextInformation contextInfo = initESB(
                configurationManager.getTracker().getCurrentConfigurationName());

        ServiceRegistration synCfgRegistration = null;
        ServiceRegistration synEnvRegistration = null;

        if (contextInfo.getSynapseConfiguration() != null) {

            //Properties props = new Properties();
            SynapseConfigurationService synCfgSvc = new SynapseConfigurationServiceImpl(
                    contextInfo.getSynapseConfiguration(), MultitenantConstants.SUPER_TENANT_ID,
                    configCtxSvc.getServerConfigContext());
            synCfgRegistration = bndCtx.registerService(SynapseConfigurationService.class.getName(), synCfgSvc,
                    null);

            initPersistence(synCfgSvc, configurationManager.getTracker().getCurrentConfigurationName());
            bndCtx.registerService(ServerShutdownHandler.class.getName(),
                    new MPMShutdownHandler(synCfgSvc.getSynapseConfiguration().getAxisConfiguration()), null);

            if (log.isDebugEnabled()) {
                log.debug("SynapseConfigurationService Registered");
            }

            if (configTrackingService != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Publishing the SynapseConfiguration to the " + "ConfigurationTrackingService");
                }
                configTrackingService.setSynapseConfiguration(contextInfo.getSynapseConfiguration());
            }

        } else {
            handleFatal(
                    "Couldn't register the SynapseConfigurationService, " + "SynapseConfiguration not found");
        }

        SynapseEnvironment synapseEnvironment = contextInfo.getSynapseEnvironment();
        if (synapseEnvironment != null) {

            //Properties props = new Properties();
            SynapseEnvironmentService synEnvSvc = new SynapseEnvironmentServiceImpl(synapseEnvironment,
                    MultitenantConstants.SUPER_TENANT_ID, configCtxSvc.getServerConfigContext());
            synEnvRegistration = bndCtx.registerService(SynapseEnvironmentService.class.getName(), synEnvSvc,
                    null);
            synapseEnvironment.registerSynapseHandler(new SynapseExternalPropertyConfigurator());
            synapseEnvironment.registerSynapseHandler(new ProxyLogHandler());

            if (log.isDebugEnabled()) {
                log.debug("SynapseEnvironmentService Registered");
            }

        } else {
            handleFatal("Couldn't register the SynapseEnvironmentService, " + "SynapseEnvironment not found");
        }

        //Properties props = new Properties();
        SynapseRegistrationsService synRegistrationsSvc = new SynapseRegistrationsServiceImpl(
                synCfgRegistration, synEnvRegistration, MultitenantConstants.SUPER_TENANT_ID,
                configCtxSvc.getServerConfigContext());
        bndCtx.registerService(SynapseRegistrationsService.class.getName(), synRegistrationsSvc, null);

        configCtxSvc.getServerConfigContext().setProperty(ConfigurationManager.CONFIGURATION_MANAGER,
                configurationManager);

        // Start Inbound Endpoint Listeners
        EndpointListenerLoader.loadListeners();

        registerInboundDeployer(configCtxSvc.getServerConfigContext().getAxisConfiguration(),
                contextInfo.getSynapseEnvironment());
    } catch (Exception e) {
        handleFatal("Couldn't initialize the ESB...", e);
    } catch (Throwable t) {
        log.fatal("Failed to initialize ESB due to a fatal error", t);
    }
}

From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java

/**
 * <p>Tests an erroneous asynchronous request where the implementation of the 
 * {@link AsyncHandler#onError(Exception)} callback throws an exception.</p>
 *  //from  w ww.  j  a  v a 2s . c  om
 * @since 1.3.0
 */
@Test
public final void testAsyncErrorCallbackError() throws InterruptedException {

    String subpath = "/errorcallbackerror", body = "non-JSON-content";

    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200).withBody(body)));

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    asyncEndpoint.asyncErrorCallbackError(new AsyncHandler<User>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, User user) {
        }

        @Override
        public void onError(InvocationException error) {

            try {

                throw new IllegalStateException();
            } finally {

                lock.lock();
                condition.signal();
                lock.unlock();
            }
        }
    });

    lock.lock();
    condition.await();
    lock.unlock();

    verify(getRequestedFor(urlEqualTo(subpath)));

    successScenario(); //verify that the asynchronous request executor has survived the exception
}

From source file:org.onosproject.drivers.bmv2.Bmv2FlowRuleProgrammable.java

private Collection<FlowRule> processFlowRules(Collection<FlowRule> rules, Operation operation) {

    if (!init()) {
        return Collections.emptyList();
    }//from ww  w. ja  v a  2  s.c  o m

    DeviceId deviceId = handler().data().deviceId();

    Bmv2DeviceAgent deviceAgent;
    try {
        deviceAgent = controller.getAgent(deviceId);
    } catch (Bmv2RuntimeException e) {
        log.error("Failed to get BMv2 device agent: {}", e.explain());
        return Collections.emptyList();
    }

    Bmv2DeviceContext context = contextService.getContext(deviceId);
    if (context == null) {
        log.error("Unable to get device context for {}", deviceId);
        return Collections.emptyList();
    }

    Bmv2FlowRuleTranslator translator = tableEntryService.getFlowRuleTranslator();

    List<FlowRule> processedFlowRules = Lists.newArrayList();

    for (FlowRule rule : rules) {

        Bmv2TableEntry bmv2Entry;

        try {
            bmv2Entry = translator.translate(rule, context);
        } catch (Bmv2FlowRuleTranslatorException e) {
            log.warn("Unable to translate flow rule: {} - {}", e.getMessage(), rule);
            continue; // next rule
        }

        String tableName = bmv2Entry.tableName();
        Bmv2TableEntryReference entryRef = new Bmv2TableEntryReference(deviceId, tableName,
                bmv2Entry.matchKey());

        Lock lock = ENTRY_LOCKS.computeIfAbsent(entryRef, k -> new ReentrantLock());
        lock.lock();
        try {
            // Get from store
            Bmv2FlowRuleWrapper frWrapper = tableEntryService.lookup(entryRef);
            try {
                if (operation == Operation.APPLY) {
                    // Apply entry
                    long entryId;
                    if (frWrapper != null) {
                        // Existing entry.
                        entryId = frWrapper.entryId();
                        // Tentatively delete entry before re-adding.
                        // It might not exist on device due to inconsistencies.
                        silentlyRemove(deviceAgent, entryRef.tableName(), entryId);
                    }
                    // Add entry.
                    entryId = doAddEntry(deviceAgent, bmv2Entry);
                    frWrapper = new Bmv2FlowRuleWrapper(rule, entryId, System.currentTimeMillis());
                } else {
                    // Remove entry
                    if (frWrapper == null) {
                        // Entry not found in map, how come?
                        forceRemove(deviceAgent, entryRef.tableName(), entryRef.matchKey());
                    } else {
                        long entryId = frWrapper.entryId();
                        doRemove(deviceAgent, entryRef.tableName(), entryId, entryRef.matchKey());
                    }
                    frWrapper = null;
                }
                // If here, no exceptions... things went well :)
                processedFlowRules.add(rule);
            } catch (Bmv2RuntimeException e) {
                log.warn("Unable to {} flow rule: {}", operation.name(), e.explain());
            }

            // Update entryRef binding in table entry service.
            if (frWrapper != null) {
                tableEntryService.bind(entryRef, frWrapper);
            } else {
                tableEntryService.unbind(entryRef);
            }
        } finally {
            lock.unlock();
        }
    }

    return processedFlowRules;
}

From source file:jenkins.plugins.git.AbstractGitSCMSource.java

protected static Lock getCacheLock(String cacheEntry) {
    Lock cacheLock;//from  w  ww  . j  a  v  a  2 s .c  o  m
    while (null == (cacheLock = cacheLocks.get(cacheEntry))) {
        cacheLocks.putIfAbsent(cacheEntry, new ReentrantLock());
    }
    return cacheLock;
}

From source file:com.haulmont.cuba.core.sys.javacl.JavaClassLoader.java

private void lock(String name) {//not sure it's right, but we can not use synchronization here
    locks.putIfAbsent(name, new ReentrantLock());
    locks.get(name).lock();//from   w ww  . ja  v  a 2 s .co  m
}

From source file:org.wso2.carbon.rest.api.service.RestApiAdminService.java

protected Lock getLock() throws APIException {
    AxisConfiguration axisConfig = ConfigHolder.getInstance().getAxisConfiguration();
    Parameter p = axisConfig.getParameter(ServiceBusConstants.SYNAPSE_CONFIG_LOCK);
    if (p != null) {
        return (Lock) p.getValue();
    } else {//w w  w  . j a  v a  2  s .  co  m
        log.warn(ServiceBusConstants.SYNAPSE_CONFIG_LOCK + " is null, Recreating a new lock");
        Lock lock = new ReentrantLock();
        try {
            axisConfig.addParameter(ServiceBusConstants.SYNAPSE_CONFIG_LOCK, lock);
            return lock;
        } catch (AxisFault axisFault) {
            log.error("Error while setting " + ServiceBusConstants.SYNAPSE_CONFIG_LOCK);
        }
    }
    return null;
}

From source file:org.apache.openjpa.kernel.StateManagerImpl.java

/**
 * Constructor; supply id, type metadata, and owning persistence manager.
 *//*from   w  w w . j  ava  2s  .  c  om*/
protected StateManagerImpl(Object id, ClassMetaData meta, BrokerImpl broker) {
    _id = id;
    _meta = meta;
    _broker = broker;
    _single = new SingleFieldManager(this, broker);
    if (broker.getMultithreaded())
        _instanceLock = new ReentrantLock();

    if (_meta.getIdentityType() == ClassMetaData.ID_UNKNOWN && !_meta.isEmbeddable())
        throw new UserException(_loc.get("meta-unknownid", _meta));
}