{"id":813,"date":"2010-06-13T09:34:52","date_gmt":"2010-06-13T07:34:52","guid":{"rendered":"http:\/\/raftaman.net\/?p=813"},"modified":"2021-05-15T11:46:40","modified_gmt":"2021-05-15T09:46:40","slug":"using-a-hashset-in-a-thread-safe-manner","status":"publish","type":"post","link":"https:\/\/possiblelossofprecision.net\/?p=813","title":{"rendered":"Using a HashSet in a thread-safe manner"},"content":{"rendered":"<p>\nThread safety is a very hot topic for Java programmers right now. But I&#8217;ve seen quite a few folks using the rather complex collections from <a href=\"http:\/\/java.sun.com\/javase\/6\/docs\/api\/java\/util\/concurrent\/package-summary.html\">java.util.concurrent<\/a> when they actually needed just a thread-safe implementation of a <a href=\"http:\/\/java.sun.com\/javase\/6\/docs\/api\/java\/util\/Set.html\">Set<\/a>.\n<\/p>\n<p>\nOf course, the <a href=\"http:\/\/java.sun.com\/javase\/6\/docs\/api\/java\/util\/HashSet.html\">HashSet<\/a> implementation is<strong> non-thread-safe<\/strong>:\n<\/p>\n<p><a href=\"http:\/\/java.sun.com\/javase\/6\/docs\/api\/java\/util\/HashSet.html\">http:\/\/java.sun.com\/javase\/6\/docs\/api\/java\/util\/HashSet.html<\/a><\/p>\n<blockquote>\n<p>\nNote that this implementation is not synchronized.  If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be &#8220;wrapped&#8221; using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set:\n<\/p>\n<\/blockquote>\n<p>\nSo getting a <strong>thread-safe<\/strong> representation of the HashSet class is pretty easy:\n<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n   Set s = Collections.synchronizedSet(new HashSet(...));\r\n<\/pre>\n<p>\nThis returns a synchronized set backed by the specified set. <strong>But be careful:<\/strong> In order to guarantee serial access, it is critical that all access to the backing set is accomplished through the returned set.\n<\/p>\n<p>\nA <strong>further pitfall<\/strong> is the use of the class&#8217;s <strong>iterator<\/strong>\n<\/p>\n<blockquote>\n<p>\nNote that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.\n<\/p>\n<\/blockquote>\n<p>\nSo it is imperative that you <strong>manually synchronize<\/strong> on the returned set when iterating over it:\n<\/p>\n<pre class=\"brush: java; highlight: [4]; title: ; notranslate\" title=\"\">\r\n  Set s = Collections.synchronizedSet(new HashSet());\r\n      ...\r\n  synchronized(s) {\r\n      Iterator i = s.iterator(); \/\/ Must be in the synchronized block\r\n      while (i.hasNext())\r\n          foo(i.next());\r\n  }\r\n <\/pre>\n<p>\nFailure to follow this advice may result in non-deterministic behavior.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Thread safety is a very hot topic for Java programmers right now. But I&#8217;ve seen quite a few folks using the rather complex collections from java.util.concurrent when they actually needed just a thread-safe implementation of a Set. Of course, the HashSet implementation is non-thread-safe: http:\/\/java.sun.com\/javase\/6\/docs\/api\/java\/util\/HashSet.html Note that this implementation is not synchronized. If multiple threads access a hash set concurrently,&#8230; <a href=\"https:\/\/possiblelossofprecision.net\/?p=813\">Read more &raquo;<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[4],"class_list":["post-813","post","type-post","status-publish","format-standard","hentry","category-uncategorized","tag-java"],"_links":{"self":[{"href":"https:\/\/possiblelossofprecision.net\/index.php?rest_route=\/wp\/v2\/posts\/813","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/possiblelossofprecision.net\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/possiblelossofprecision.net\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/possiblelossofprecision.net\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/possiblelossofprecision.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=813"}],"version-history":[{"count":9,"href":"https:\/\/possiblelossofprecision.net\/index.php?rest_route=\/wp\/v2\/posts\/813\/revisions"}],"predecessor-version":[{"id":822,"href":"https:\/\/possiblelossofprecision.net\/index.php?rest_route=\/wp\/v2\/posts\/813\/revisions\/822"}],"wp:attachment":[{"href":"https:\/\/possiblelossofprecision.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=813"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/possiblelossofprecision.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=813"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/possiblelossofprecision.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=813"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}