Search in sources :

Example 91 with ConcurrentHashMap

use of java.util.concurrent.ConcurrentHashMap in project azure-iot-sdk-java by Azure.

the class AmqpsTransportTest method isEmptyReturnsFalseIfInProgressMapIsNotEmpty.

// Tests_SRS_AMQPSTRANSPORT_15_035: [The function shall return true if the waiting list,
// in progress list and callback list are all empty, and false otherwise.]
@Test
public void isEmptyReturnsFalseIfInProgressMapIsNotEmpty() throws IOException {
    AmqpsTransport transport = new AmqpsTransport(mockConfig, false);
    Map<Integer, IotHubOutboundPacket> inProgressMessages = new ConcurrentHashMap<>();
    inProgressMessages.put(1, new IotHubOutboundPacket(new Message(), mockIotHubEventCallback, new Object()));
    Deencapsulation.setField(transport, "inProgressMessages", inProgressMessages);
    Boolean isEmpty = transport.isEmpty();
    Assert.assertFalse(isEmpty);
}
Also used : AmqpsTransport(com.microsoft.azure.sdk.iot.device.transport.amqps.AmqpsTransport) AmqpsMessage(com.microsoft.azure.sdk.iot.device.transport.amqps.AmqpsMessage) IotHubOutboundPacket(com.microsoft.azure.sdk.iot.device.transport.IotHubOutboundPacket) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Test(org.junit.Test)

Example 92 with ConcurrentHashMap

use of java.util.concurrent.ConcurrentHashMap in project OkHttp3 by MrZhousf.

the class DownUpLoadHelper method downloadFile.

/**
     * 文件下载
     */
void downloadFile(final OkHttpHelper helper) {
    try {
        final HttpInfo info = httpInfo;
        final DownloadFileInfo fileInfo = helper.getDownloadFileInfo();
        String url = fileInfo.getUrl();
        if (TextUtils.isEmpty(url)) {
            showLog("下载文件失败:文件下载地址不能为空!");
            return;
        }
        info.setUrl(url);
        ProgressCallback progressCallback = fileInfo.getProgressCallback();
        //获取文件断点
        long completedSize = fetchCompletedSize(fileInfo);
        fileInfo.setCompletedSize(completedSize);
        //添加下载任务
        if (null == downloadTaskMap)
            downloadTaskMap = new ConcurrentHashMap<>();
        if (downloadTaskMap.containsKey(fileInfo.getSaveFileNameEncrypt())) {
            showLog(fileInfo.getSaveFileName() + " 已在下载任务中");
            return;
        }
        downloadTaskMap.put(fileInfo.getSaveFileNameEncrypt(), fileInfo.getSaveFileNameEncrypt());
        Interceptor interceptor = new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder().body(new ProgressResponseBody(originalResponse.body(), fileInfo, timeStamp, requestTag)).build();
            }
        };
        //采用新的OkHttpClient处理多线程干扰回调进度问题
        OkHttpClient httpClient = helper.getClientBuilder().addInterceptor(interceptor).build();
        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(url).header("RANGE", "bytes=" + completedSize + "-");
        helper.getHttpHelper().addHeadsToRequest(info, requestBuilder);
        Request request = requestBuilder.build();
        helper.setRequest(request);
        helper.setHttpClient(httpClient);
        helper.getHttpHelper().responseCallback(helper.doRequestSync(), progressCallback, OkMainHandler.RESPONSE_DOWNLOAD_CALLBACK, requestTag);
        //删除下载任务
        if (null != downloadTaskMap) {
            downloadTaskMap.remove(fileInfo.getSaveFileNameEncrypt());
        }
    } catch (Exception e) {
        showLog("下载文件失败:" + e.getMessage());
    }
}
Also used : DownloadFileInfo(com.okhttplib.bean.DownloadFileInfo) OkHttpClient(okhttp3.OkHttpClient) ProgressCallback(com.okhttplib.callback.ProgressCallback) Request(okhttp3.Request) ProgressResponseBody(com.okhttplib.progress.ProgressResponseBody) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) HttpInfo(com.okhttplib.HttpInfo) Response(okhttp3.Response) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Interceptor(okhttp3.Interceptor)

Example 93 with ConcurrentHashMap

use of java.util.concurrent.ConcurrentHashMap in project kdeconnect-android by KDE.

the class DeviceFragment method refreshUI.

void refreshUI() {
    if (device == null || rootView == null) {
        return;
    }
    //Once in-app, there is no point in keep displaying the notification if any
    device.hidePairingNotification();
    mActivity.runOnUiThread(new Runnable() {

        @Override
        public void run() {
            if (device.isPairRequestedByPeer()) {
                ((TextView) rootView.findViewById(R.id.pair_message)).setText(R.string.pair_requested);
                rootView.findViewById(R.id.pair_progress).setVisibility(View.GONE);
                rootView.findViewById(R.id.pair_button).setVisibility(View.GONE);
                rootView.findViewById(R.id.pair_request).setVisibility(View.VISIBLE);
            } else {
                boolean paired = device.isPaired();
                boolean reachable = device.isReachable();
                boolean onData = NetworkHelper.isOnMobileNetwork(getContext());
                rootView.findViewById(R.id.pairing_buttons).setVisibility(paired ? View.GONE : View.VISIBLE);
                rootView.findViewById(R.id.not_reachable_message).setVisibility((paired && !reachable && !onData) ? View.VISIBLE : View.GONE);
                rootView.findViewById(R.id.on_data_message).setVisibility((paired && !reachable && onData) ? View.VISIBLE : View.GONE);
                try {
                    ArrayList<ListAdapter.Item> items = new ArrayList<>();
                    //Plugins button list
                    final Collection<Plugin> plugins = device.getLoadedPlugins().values();
                    for (final Plugin p : plugins) {
                        if (!p.hasMainActivity())
                            continue;
                        if (p.displayInContextMenu())
                            continue;
                        items.add(new PluginItem(p, new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                p.startMainActivity(mActivity);
                            }
                        }));
                    }
                    //Failed plugins List
                    final ConcurrentHashMap<String, Plugin> failed = device.getFailedPlugins();
                    if (!failed.isEmpty()) {
                        if (errorHeader == null) {
                            errorHeader = new TextView(mActivity);
                            errorHeader.setPadding(0, ((int) (28 * getResources().getDisplayMetrics().density)), 0, ((int) (8 * getResources().getDisplayMetrics().density)));
                            errorHeader.setOnClickListener(null);
                            errorHeader.setOnLongClickListener(null);
                            errorHeader.setText(getResources().getString(R.string.plugins_failed_to_load));
                        }
                        items.add(new CustomItem(errorHeader));
                        for (Map.Entry<String, Plugin> entry : failed.entrySet()) {
                            String pluginKey = entry.getKey();
                            final Plugin plugin = entry.getValue();
                            if (plugin == null) {
                                items.add(new SmallEntryItem(pluginKey));
                            } else {
                                items.add(new SmallEntryItem(plugin.getDisplayName(), new View.OnClickListener() {

                                    @Override
                                    public void onClick(View v) {
                                        plugin.getErrorDialog(mActivity).show();
                                    }
                                }));
                            }
                        }
                    }
                    //Plugins without permissions List
                    final ConcurrentHashMap<String, Plugin> permissionsNeeded = device.getPluginsWithoutPermissions();
                    if (!permissionsNeeded.isEmpty()) {
                        if (noPermissionsHeader == null) {
                            noPermissionsHeader = new TextView(mActivity);
                            noPermissionsHeader.setPadding(0, ((int) (28 * getResources().getDisplayMetrics().density)), 0, ((int) (8 * getResources().getDisplayMetrics().density)));
                            noPermissionsHeader.setOnClickListener(null);
                            noPermissionsHeader.setOnLongClickListener(null);
                            noPermissionsHeader.setText(getResources().getString(R.string.plugins_need_permission));
                        }
                        items.add(new CustomItem(noPermissionsHeader));
                        for (Map.Entry<String, Plugin> entry : permissionsNeeded.entrySet()) {
                            String pluginKey = entry.getKey();
                            final Plugin plugin = entry.getValue();
                            if (plugin == null) {
                                items.add(new SmallEntryItem(pluginKey));
                            } else {
                                items.add(new SmallEntryItem(plugin.getDisplayName(), new View.OnClickListener() {

                                    @Override
                                    public void onClick(View v) {
                                        plugin.getPermissionExplanationDialog(mActivity).show();
                                    }
                                }));
                            }
                        }
                    }
                    ListView buttonsList = (ListView) rootView.findViewById(R.id.buttons_list);
                    ListAdapter adapter = new ListAdapter(mActivity, items);
                    buttonsList.setAdapter(adapter);
                    mActivity.invalidateOptionsMenu();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                //Ignore: The activity was closed while we were trying to update it
                } catch (ConcurrentModificationException e) {
                    Log.e("DeviceActivity", "ConcurrentModificationException");
                    //Try again
                    this.run();
                }
            }
        }
    });
}
Also used : CustomItem(org.kde.kdeconnect.UserInterface.List.CustomItem) ConcurrentModificationException(java.util.ConcurrentModificationException) ArrayList(java.util.ArrayList) View(android.view.View) TextView(android.widget.TextView) ListView(android.widget.ListView) SmallEntryItem(org.kde.kdeconnect.UserInterface.List.SmallEntryItem) ListView(android.widget.ListView) Collection(java.util.Collection) TextView(android.widget.TextView) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) PluginItem(org.kde.kdeconnect.UserInterface.List.PluginItem) ListAdapter(org.kde.kdeconnect.UserInterface.List.ListAdapter) Plugin(org.kde.kdeconnect.Plugins.Plugin)

Example 94 with ConcurrentHashMap

use of java.util.concurrent.ConcurrentHashMap in project jdk8u_jdk by JetBrains.

the class ConcurrentAssociateTest method testOnce.

private static void testOnce(String desc, BiConsumer<ConcurrentMap<Object, Object>, Object> associator) {
    ConcurrentHashMap<Object, Object> m = new ConcurrentHashMap<>();
    CountDownLatch s = new CountDownLatch(1);
    Supplier<Runnable> sr = () -> () -> {
        try {
            s.await();
        } catch (InterruptedException e) {
        }
        for (int i = 0; i < N; i++) {
            Object o = new X();
            associator.accept(m, o);
            if (!m.containsKey(o)) {
                throw new AssociationFailure(desc + " failed: entry does not exist");
            }
        }
    };
    int ps = Runtime.getRuntime().availableProcessors();
    Stream<CompletableFuture> runners = IntStream.range(0, ps).mapToObj(i -> sr.get()).map(CompletableFuture::runAsync);
    CompletableFuture all = CompletableFuture.allOf(runners.toArray(CompletableFuture[]::new));
    // Trigger the runners to start associating
    s.countDown();
    try {
        all.join();
    } catch (CompletionException e) {
        Throwable t = e.getCause();
        if (t instanceof AssociationFailure) {
            throw (AssociationFailure) t;
        } else {
            throw e;
        }
    }
}
Also used : IntStream(java.util.stream.IntStream) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Test(org.testng.annotations.Test) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) CompletionException(java.util.concurrent.CompletionException) Supplier(java.util.function.Supplier) ConcurrentMap(java.util.concurrent.ConcurrentMap) CountDownLatch(java.util.concurrent.CountDownLatch) Stream(java.util.stream.Stream) Map(java.util.Map) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) BiConsumer(java.util.function.BiConsumer) CountDownLatch(java.util.concurrent.CountDownLatch) CompletableFuture(java.util.concurrent.CompletableFuture) CompletionException(java.util.concurrent.CompletionException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 95 with ConcurrentHashMap

use of java.util.concurrent.ConcurrentHashMap in project dubbo by alibaba.

the class RegistryServerSync method notify.

// 收到的通知对于 ,同一种类型数据(override、subcribe、route、其它是Provider),同一个服务的数据是全量的
public void notify(List<URL> urls) {
    if (urls == null || urls.isEmpty()) {
        return;
    }
    // Map<category, Map<servicename, Map<Long, URL>>>
    final Map<String, Map<String, Map<Long, URL>>> categories = new HashMap<String, Map<String, Map<Long, URL>>>();
    for (URL url : urls) {
        String category = url.getParameter(Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY);
        if (Constants.EMPTY_PROTOCOL.equalsIgnoreCase(url.getProtocol())) {
            // 注意:empty协议的group和version为*
            ConcurrentMap<String, Map<Long, URL>> services = registryCache.get(category);
            if (services != null) {
                String group = url.getParameter(Constants.GROUP_KEY);
                String version = url.getParameter(Constants.VERSION_KEY);
                // 注意:empty协议的group和version为*
                if (!Constants.ANY_VALUE.equals(group) && !Constants.ANY_VALUE.equals(version)) {
                    services.remove(url.getServiceKey());
                } else {
                    for (Map.Entry<String, Map<Long, URL>> serviceEntry : services.entrySet()) {
                        String service = serviceEntry.getKey();
                        if (Tool.getInterface(service).equals(url.getServiceInterface()) && (Constants.ANY_VALUE.equals(group) || StringUtils.isEquals(group, Tool.getGroup(service))) && (Constants.ANY_VALUE.equals(version) || StringUtils.isEquals(version, Tool.getVersion(service)))) {
                            services.remove(service);
                        }
                    }
                }
            }
        } else {
            Map<String, Map<Long, URL>> services = categories.get(category);
            if (services == null) {
                services = new HashMap<String, Map<Long, URL>>();
                categories.put(category, services);
            }
            String service = url.getServiceKey();
            Map<Long, URL> ids = services.get(service);
            if (ids == null) {
                ids = new HashMap<Long, URL>();
                services.put(service, ids);
            }
            ids.put(ID.incrementAndGet(), url);
        }
    }
    for (Map.Entry<String, Map<String, Map<Long, URL>>> categoryEntry : categories.entrySet()) {
        String category = categoryEntry.getKey();
        ConcurrentMap<String, Map<Long, URL>> services = registryCache.get(category);
        if (services == null) {
            services = new ConcurrentHashMap<String, Map<Long, URL>>();
            registryCache.put(category, services);
        }
        services.putAll(categoryEntry.getValue());
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) URL(com.alibaba.dubbo.common.URL) AtomicLong(java.util.concurrent.atomic.AtomicLong) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map)

Aggregations

ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)420 Map (java.util.Map)106 Test (org.junit.Test)102 HashMap (java.util.HashMap)75 ArrayList (java.util.ArrayList)73 CountDownLatch (java.util.concurrent.CountDownLatch)53 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)49 IOException (java.io.IOException)47 List (java.util.List)38 Set (java.util.Set)36 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)33 HashSet (java.util.HashSet)31 AtomicLong (java.util.concurrent.atomic.AtomicLong)29 ConcurrentMap (java.util.concurrent.ConcurrentMap)28 Random (java.util.Random)25 ExecutorService (java.util.concurrent.ExecutorService)23 Collection (java.util.Collection)20 UUID (java.util.UUID)20 Iterator (java.util.Iterator)19 Configuration (org.apache.hadoop.conf.Configuration)17