Search Results

Search found 395 results on 16 pages for 'acquire'.

Page 2/16 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • XSF-FO intellisense and national languages with Apache FOP

    - by Lukasz Kurylo
    Some time ago I showed how to get an intellisense and how to configure the FO.NET to acquire national characters inside the generated pdf files. Due to the limitations that I mensioned in my previous post, I started playing with the Apache FOP. In this post I want to show, how to acquire the same result as I showed in the two posts related to FO.NET.   Intellisense   To get the intellisense from the XSL-FO templates set the xsi:schemaLocation the same way I showed it in this post. The only diffrence to FO.NET is that, during generating the document by the code I showed last time we will get an exception:   org.apache.fop.fo.ValidationException: Invalid property encountered on "fo:root": xsi:schemaLocation (See position 6:11)   Fortunatelly there is a very easy way to resolve this without removing the entire attribute along with the intellisense. Add to the FopFactory the ignoreNamespace by:   FopFactory fopFactory = FopFactory.newInstance(); fopFactory.ignoreNamespace(http://www.w3.org/2001/XMLSchema-instance);   Notice that, the url specified in this method this is a namespace for the xmlns:xsi namespace, not xsi.schemaLocation.   Fonts / national characters   This point is a little dfferent to acquire, but not more complicated that it was with FO.NET. To set the fonts in Apache FOP 1.0, we need a configuration file. A sample one can be get from the directory where we unpacked the fop binaries, from conf subdirectory. There is a file called fop.xconf. We must copy this file to our solution. In the simplest way, in the <fonts> tag we can add  <auto-detect/>. Thanks to this, FOP will index all fonts available on the installed operating system. There probably should be no problem, if we have a http handler or a WCF Service on the server that serves the generated pdf documents. In this situation we can use all available fonts on this server.   To use this config file, we must set a path to it:   FopFactory fopFactory = FopFactory.newInstance(); fopFactory.setUserConfig(new File("fop.xconf"));

    Read the article

  • Python Locking Implementation (with threading module)

    - by Matty
    This is probably a rudimentary question, but I'm new to threaded programming in Python and am not entirely sure what the correct practice is. Should I be creating a single lock object (either globally or being passed around) and using that everywhere that I need to do locking? Or, should I be creating multiple lock instances in each of the classes where I will be employing them. Take these 2 rudimentary code samples, which direction is best to go? The main difference being that a single lock instance is used in both class A and B in the second, while multiple instances are used in the first. Sample 1 class A(): def __init__(self, theList): self.theList = theList self.lock = threading.Lock() def poll(self): while True: # do some stuff that eventually needs to work with theList self.lock.acquire() try: self.theList.append(something) finally: self.lock.release() class B(threading.Thread): def __init__(self,theList): self.theList = theList self.lock = threading.Lock() self.start() def run(self): while True: # do some stuff that eventually needs to work with theList self.lock.acquire() try: self.theList.remove(something) finally: self.lock.release() if __name__ == "__main__": aList = [] for x in range(10): B(aList) A(aList).poll() Sample 2 class A(): def __init__(self, theList,lock): self.theList = theList self.lock = lock def poll(self): while True: # do some stuff that eventually needs to work with theList self.lock.acquire() try: self.theList.append(something) finally: self.lock.release() class B(threading.Thread): def __init__(self,theList,lock): self.theList = theList self.lock = lock self.start() def run(self): while True: # do some stuff that eventually needs to work with theList self.lock.acquire() try: self.theList.remove(something) finally: self.lock.release() if __name__ == "__main__": lock = threading.Lock() aList = [] for x in range(10): B(aList,lock) A(aList,lock).poll()

    Read the article

  • Windows 8 Professional didn't come with Internet Explorer 10(Metro)

    - by Joel Dean
    When I installed Windows 8 Professional Edition I noticed that Internet Explorer 10 was missing. I tried to find some source to acquire the installer but none of the sites are providing it. One of my colleagues upgraded recently and he got the new Internet Explorer after his installation was completed. So is there a way to acquire the installer? Update: I should have mentioned that I was talking about the Metro version.

    Read the article

  • SQL Server 2008 Dead lock issue

    - by user173552
    I got into a deadlock issue where I am struggling find the root-cause...The Deadlock graph suggests that an UPDATE statement became the victim over a SELECT statement... What puzzles me is that the UPDATE statement is trying to acquire an index on some other table that is never referred in update statement... This is how my UPDATE statement looks like... UPDATE Table set col1 = @P1 where col2 = @P2 This statement acquired a X lock on the col2 index, but also tries to acquire an index on a column defined in some other table that is no way related to the UPDATE statement... And the SELECT statement that won the deadlock situation had nothing to do with the table or index in the update statement but tried to acquire an index on the table in UPDATE statement. eventually causing the DEADLOCK.

    Read the article

  • Proper way to 100% wakes my device?

    - by quiel
    Do you have better way to make the device awakes by 100%? I repeatedly call the acquire() but I'm not sure if that is correct. Or should I just call the acquire() once? Or should I make use of Intent.ACTION_SCREEN_OFF? public class MyServiceThatKeepsTheDeviceAwake extends IntentService { ... @Override public void onCreate() { super.onCreate(); mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = mPowerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.ON_AFTER_RELEASE, TAG); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); mWakeLock.acquire(); } // No release

    Read the article

  • How can I run a Unity session inside Xephyr?

    - by d3vid
    I can get Xephyr to run single applications within a Xephyr window. How can I run an entire Unity desktop session within a Xephyr window? (Preferably as another user.) If I use the gtk-xephyr script with the command gnome-session --session=ubuntu, I get a black window. If I run compiz I get a grey window. If I do not use the script and just run the following I get a popup in the Xephyr window saying "Could not acquire name on session bus. [Log out]" and in the terminal "gnome-session[3157]: WARNING: Failed to acquire org.gnome.SessionManager". Xephyr :8 & DISPLAY=:8 gnome-session --session=ubuntu

    Read the article

  • Ubuntu Extras keyring error

    - by Pawan Neupane
    Recently I got lots of GPG errors and tried the following methods at various stages: sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 3E5C1192 sudo apt-get install -reinstall ubuntu-extras-keyring (For Ubuntu Extras only) gpg –keyserver keyserver.ubuntu.com –recv 3E5C1192 gpg –export –armor 3E5C1192 | sudo apt-key add - sudo apt-get update sudo aptitude -o Acquire::http::No-Cache=True -o Acquire::BrokenProxy=true update sudo -i apt-get clean cd /var/lib/apt mv lists lists.old mkdir -p lists/partial apt-get clean apt-get update I again got BADSIG error for extras.ubuntu.com today. So, I'm really at a loss what's causing this error to occur time and again. I really want to solve this problem once and for all.

    Read the article

  • Proxy settings do not promulgate to fat or thin clients

    - by solizin47
    I work in Hertfordshire schools, which use a proxy eg http://wf1.thegrid.org.uk on port 80 to allow graded access by all users, within the schools, to the Internet. I have Ubuntu 10.04LTS successfully running and I want to set up 12.04LTS to replace it. Many other replies to this question have answered questions about stand-alone computers and not addressed the LTSP server and its clients. I have come to a complete stop over the problem of the proxy server settings not promulgating over the local network to Ubuntu 12.04 thin or fat clients. When you input this setting (there are others for HTTPS and FTP) into the System Settings/Network Manager GUI on the server, then when a user logs into the server, both Firefox and Chrome can read the settings and will gain access to the Internet. HOWEVER, these settings are not promulgated to either thin or fat clients on the local network. Their System Settings/Network Manager GUI remains stubbornly blank. I have rebuilt the image after inputting the proxy settings, but it appears they are not part of the image. /etc/environment (on the server) already has: PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games" http_proxy="http://wf1.thegrid.org.uk:80/" https_proxy="https://wf1.thegrid.org.uk:80/" ftp_proxy="ftp://proxy.intra.thegrid.org.uk:3128/" I have also tried this export http_proxy="http://wf1.thegrid.org.uk:80" export https_proxy="http://wf1.thegrid.org.uk:80" export ftp_proxy="http://proxy.intra.thegrid.org.uk:3128" within /etc/environment, and that had no effect, either. etc/apt/apt.conf also has: Acquire::http::proxy "http://wf1.thegrid.org.uk:80/"; Acquire::https::proxy "https://wf1.thegrid.org.uk:80/"; Acquire::ftp::proxy "ftp://proxy.intra.thegrid.org.uk:3128/"; The clients still have no proxy settings in their Network Manager, and no client user can access the Internet from Firefox or Chrome. Three questions: Why doesn't the “Apply system wide” button work? It does on 10.04, and every new user, and all existing users have access to the internet through the proxy without problem. How can I set up proxy settings that work for all the 12.04 clients? I noticed that if user West input the settings himself, they would follow him around the clients. However, this is not secure, because there are grades of settings which prevent visits to various sites, eg wf3 allows fewer sites than wf2 or wf1, so I can't allow users to input this setting themselves. Since the proxy setting followed the user around the clients, the setting must be somewhere in the user profile, since none of the other users have the proxy settings. Do you know where, and how I could fix the setting for users, or better, groups? The setting must then be unchangeable by the user, with no access to the Network Manager. If either 2. or 3. can't be done, then the Ubuntu 12.04LTS server is simply no use to us...

    Read the article

  • Topics for covering in-depth programming knowledge

    - by black_belt
    I pursued my bachelors' degree in business administration, but my interest in Information Technology led me to acquire some knowledge of PHP programming and MySQL database. I find programming so interesting that I haven't applied for any job since my graduation. Currently I am staying home and just trying to acquire in-depth knowledge of PHP programming. So far I have developed couple of websites and web applications including Inventory+ Point of Sale Software and an Accounting system for small organizations. I aim to have knowledge that a Computer Science graduate should have, and for that I want to read books but I have no idea where to start from. Could you please suggest me some books and topics that I should study on? Thanks a lot :)

    Read the article

  • How is spin lock implemented under the hood?

    - by httpinterpret
    This is a lock that can be held by only one thread of execution at a time. An attempt to acquire the lock by another thread of execution makes the latter loop until the lock is released. How does it handle the case when two threads try to acquire the lock exactly the same time? I think this question also applies to various of other mutex implementation.

    Read the article

  • In Java What is the guaranteed way to get a FileLock from FileChannel while accessing a RandomAcces

    - by narasimha.bhat
    I am trying to use FileLock lock(long position, long size,boolean shared) in FileChannel object As per the javadoc it can throw OverlappingFileLockException. When I create a test program with 2 threads lock method seems to be waiting to acquire the lock (both exclusive and non exclusive) But when the number threads increases in the acutal scenario over lapping file lock exception is thrown and processing slows down due the block at File lock table. What is the best way to acquire lock avoiding the OverlappingFileLockException ?

    Read the article

  • deadlock because of foreign key?

    - by George2
    Hello everyone, I am using SQL Server 2008 Enterprise. I met with deadlock in the following store procedure, but because of my fault, I did not record the deadlock graph. But now I can not reproduce deadlock issue. I want to have a postmortem to find the root cause of deadlock to avoid deadlock in the future. The deadlock happens on delete statement. For the delete statement, Param1 is a column of table FooTable, Param1 is a foreign key of another table (refers to another primary key clustered index column of the other table). There is no index on Param1 itself for table FooTable. FooTable has another column which is used as clustered primary key, but not Param1 column. Here is my guess why there is deadlock, and I want to let people review whether my analysis is correct? Since Param1 column has no index, there will be a table scan, and will acquire table level lock, because of foreign key, the delete operation will also need to check master table (e.g. to acquire lock on master table); Some operation on master table acquires master table lock, but want to acquire lock on FooTable; (1) and (2) cause cycle lock which makes deadlock happen. My analysis correct? Any reproduce scenario? create PROCEDURE [dbo].[FooProc] ( @Param1 int ,@Param2 int ,@Param3 int ) AS DELETE FooTable WHERE Param1 = @Param1 INSERT INTO FooTable ( Param1 ,Param2 ,Param3 ) VALUES ( @Param1 ,@Param2 ,@Param3 ) DECLARE @ID bigint SET @ID = ISNULL(@@Identity,-1) IF @ID > 0 BEGIN SELECT IdentityStr FROM FooTable WHERE ID = @ID END thanks in advance, George

    Read the article

  • strange behavior in python

    - by fsm
    The tags might not be accurate since I am not sure where the problem is. I have a module where I am trying to read some data from a socket, and write the results into a file (append) It looks something like this, (only relevant parts included) if __name__ == "__main__": <some init code> for line in file: t = Thread(target=foo, args=(line,)) t.start() while nThreads > 0: time.sleep(1) Here are the other modules, def foo(text): global countLock, nThreads countLock.acquire() nThreads += 1 countLock.release() """connect to socket, send data, read response""" writeResults(text, result) countLock.acquire() nThreads -= 1 countLock.release() def writeResults(text, result): """acquire file lock""" """append to file""" """release file lock""" Now here's the problem. Initially, I had a typo in the function 'foo', where I was passing the variable 'line' to writeResults instead of 'text'. 'line' is not defined in the function foo, it's defined in the main block, so I should have seen an error, but instead, it worked fine, except that the data was appended to the file multiple times, instead of being written just once, which is the required behavior, which I got when I fixed the typo. My question is, 1) Why didn't I get an error? 2) Why was the writeResults function being called multiple times?

    Read the article

  • error 503: service unavailable when using apt-get update behind proxy

    - by ubuntu2man
    Hi, I am using a transparent proxy (other box). When I try to do an 'apt-get update' I get these warnings (in german): ... W: Fehlschlag beim Holen von http://security.ubuntu.com/ubuntu/dists/maverick-security/restricted/source/Sources.gz 503 Service Unavailable W: Fehlschlag beim Holen von http://security.ubuntu.com/ubuntu/dists/maverick-security/universe/source/Sources.gz 503 Service Unavailable W: Fehlschlag beim Holen von http://security.ubuntu.com/ubuntu/dists/maverick-security/multiverse/source/Sources.gz 503 Service Unavailable W: Fehlschlag beim Holen von http://security.ubuntu.com/ubuntu/dists/maverick-security/main/binary-i386/Packages.gz 503 Service Unavailable W: Fehlschlag beim Holen von http://security.ubuntu.com/ubuntu/dists/maverick-security/restricted/binary-i386/Packages.gz 503 Service Unavailable W: Fehlschlag beim Holen von http://security.ubuntu.com/ubuntu/dists/maverick-security/universe/binary-i386/Packages.gz 503 Service Unavailable E: Einige Indexdateien konnten nicht heruntergeladen werden, sie wurden ignoriert oder alte an ihrer Stelle benutzt. I changed ~.bashrc: http_proxy=http://192.168.120.199:8080 https_proxy=https://192.168.120:8080 export http_proxy export https_proxy I wrote on commandline: export http_proxy=http://proxyusername:proxypassword@proxyaddress:proxyport sudo apt-get update And I edited /etc/apt/apt.conf: Acquire::http::proxy "http://192.168.120.199:8080/"; Acquire::ftp::proxy "http://192.168.120.199:8080/"; Nothing has worked. Does anyone knows how to make apt-get working through a transparent proxy? Regards, ubuntu2man

    Read the article

  • Change sysout logging level for Weblogic

    - by Justin Voss
    When I run a local copy of Weblogic, I like to see the output in the console so that I can observe my app's logging messages. But, Weblogic spits out a lot of log messages I don't care about, like these: [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)' 08-29-2010 01:02:21 INFO Getting a JNDI connection [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)' 08-29-2010 01:02:21 INFO Connection Returned. Elapsed time to acquire=0ms. [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)' 08-29-2010 01:02:21 INFO Getting a JNDI connection [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)' 08-29-2010 01:02:21 INFO Connection Returned. Elapsed time to acquire=0ms. Can I configure Weblogic to not output those? I assume that I can change the logging level to something higher than INFO and that should fix it?

    Read the article

  • Change sysout logging level for Weblogic

    - by Justin Voss
    When I run a local copy of Weblogic, I like to see the output in the console so that I can observe my app's logging messages. But, Weblogic spits out a lot of log messages I don't care about, like these: [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)' 08-29-2010 01:02:21 INFO Getting a JNDI connection [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)' 08-29-2010 01:02:21 INFO Connection Returned. Elapsed time to acquire=0ms. [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)' 08-29-2010 01:02:21 INFO Getting a JNDI connection [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)' 08-29-2010 01:02:21 INFO Connection Returned. Elapsed time to acquire=0ms. Can I configure Weblogic to not output those? I assume that I can change the logging level to something higher than INFO and that should fix it?

    Read the article

  • GPG Invalid Signature

    - by user46421
    I am having problems with the following (in an attempt to remove hyperlinks, I have removed one of the "/" from the addresses): W: GPG error: http://archive.ubuntu.com oneiric Release: The following signatures were invalid: BADSIG 40976EAF437D05B5 Ubuntu Archive Automatic Signing Key <[email protected]> W: GPG error: http://ppa.launchpad.net oneiric Release: The following signatures were invalid: BADSIG B725097B3ACC3965 Launchpad lffl W: GPG error: http://ppa.launchpad.net oneiric Release: The following signatures were invalid: BADSIG 4874D3686E80C6B7 Launchpad PPA for Banshee Team W: GPG error: http://archive.getdeb.net jaunty-getdeb Release: The following signatures were invalid: BADSIG A8A515F046D7E7CF GetDeb Archive Automatic Signing Key <[email protected]> W: GPG error: http://badgerports.org lucid Release: The following signatures were invalid: BADSIG C90F9CB90E1FAD0C Jo Shields <[email protected]> W: GPG error: http://ppa.launchpad.net oneiric Release: The following signatures were invalid: BADSIG 976B5901365C5CA1 Launchpad PPA for transmissionbt W: Failed to fetch http://ppa.launchpad.net/dlecan/openjdk/ubuntu/dists/oneiric/main/source/Sources 404 Not Found W: Failed to fetch http://ppa.launchpad.net/dlecan/openjdk/ubuntu/dists/oneiric/main/binary-i386/Packages 404 Not Found W: Failed to fetch http://ppa.launchpad.net/sevenmachines/flash/ubuntu/dists/oneiric/main/binary-i386/Packages 404 Not Found W: Failed to fetch http://ppa.launchpad.net/sun-java-community-team/sun-java6/ubuntu/dists/oneiric/main/source/Sources 404 Not Found W: Failed to fetch http://ppa.launchpad.net/sun-java-community-team/sun-java6/ubuntu/dists/oneiric/main/binary-i386/Packages 404 Not Found I have tried the following solutions which were in a closed case titled "The following signatures were invalid": First of all try sudo apt-get clean sudo apt-get update && sudo apt-get upgrade Some ISPs cache the packages and errors like these are reported then. If the above commands don't work, try sudo apt-get update -o Acquire::http::No-Cache=True and again sudo apt-get update && sudo apt-get upgrade If it still doesn't work, sudo apt-get update -o Acquire::BrokenProxy=true sudo apt-get update && sudo apt-get upgrade

    Read the article

  • Inside the Concurrent Collections: ConcurrentDictionary

    - by Simon Cooper
    Using locks to implement a thread-safe collection is rather like using a sledgehammer - unsubtle, easy to understand, and tends to make any other tool redundant. Unlike the previous two collections I looked at, ConcurrentStack and ConcurrentQueue, ConcurrentDictionary uses locks quite heavily. However, it is careful to wield locks only where necessary to ensure that concurrency is maximised. This will, by necessity, be a higher-level look than my other posts in this series, as there is quite a lot of code and logic in ConcurrentDictionary. Therefore, I do recommend that you have ConcurrentDictionary open in a decompiler to have a look at all the details that I skip over. The problem with locks There's several things to bear in mind when using locks, as encapsulated by the lock keyword in C# and the System.Threading.Monitor class in .NET (if you're unsure as to what lock does in C#, I briefly covered it in my first post in the series): Locks block threads The most obvious problem is that threads waiting on a lock can't do any work at all. No preparatory work, no 'optimistic' work like in ConcurrentQueue and ConcurrentStack, nothing. It sits there, waiting to be unblocked. This is bad if you're trying to maximise concurrency. Locks are slow Whereas most of the methods on the Interlocked class can be compiled down to a single CPU instruction, ensuring atomicity at the hardware level, taking out a lock requires some heavy lifting by the CLR and the operating system. There's quite a bit of work required to take out a lock, block other threads, and wake them up again. If locks are used heavily, this impacts performance. Deadlocks When using locks there's always the possibility of a deadlock - two threads, each holding a lock, each trying to aquire the other's lock. Fortunately, this can be avoided with careful programming and structured lock-taking, as we'll see. So, it's important to minimise where locks are used to maximise the concurrency and performance of the collection. Implementation As you might expect, ConcurrentDictionary is similar in basic implementation to the non-concurrent Dictionary, which I studied in a previous post. I'll be using some concepts introduced there, so I recommend you have a quick read of it. So, if you were implementing a thread-safe dictionary, what would you do? The naive implementation is to simply have a single lock around all methods accessing the dictionary. This would work, but doesn't allow much concurrency. Fortunately, the bucketing used by Dictionary allows a simple but effective improvement to this - one lock per bucket. This allows different threads modifying different buckets to do so in parallel. Any thread making changes to the contents of a bucket takes the lock for that bucket, ensuring those changes are thread-safe. The method that maps each bucket to a lock is the GetBucketAndLockNo method: private void GetBucketAndLockNo( int hashcode, out int bucketNo, out int lockNo, int bucketCount) { // the bucket number is the hashcode (without the initial sign bit) // modulo the number of buckets bucketNo = (hashcode & 0x7fffffff) % bucketCount; // and the lock number is the bucket number modulo the number of locks lockNo = bucketNo % m_locks.Length; } However, this does require some changes to how the buckets are implemented. The 'implicit' linked list within a single backing array used by the non-concurrent Dictionary adds a dependency between separate buckets, as every bucket uses the same backing array. Instead, ConcurrentDictionary uses a strict linked list on each bucket: This ensures that each bucket is entirely separate from all other buckets; adding or removing an item from a bucket is independent to any changes to other buckets. Modifying the dictionary All the operations on the dictionary follow the same basic pattern: void AlterBucket(TKey key, ...) { int bucketNo, lockNo; 1: GetBucketAndLockNo( key.GetHashCode(), out bucketNo, out lockNo, m_buckets.Length); 2: lock (m_locks[lockNo]) { 3: Node headNode = m_buckets[bucketNo]; 4: Mutate the node linked list as appropriate } } For example, when adding another entry to the dictionary, you would iterate through the linked list to check whether the key exists already, and add the new entry as the head node. When removing items, you would find the entry to remove (if it exists), and remove the node from the linked list. Adding, updating, and removing items all follow this pattern. Performance issues There is a problem we have to address at this point. If the number of buckets in the dictionary is fixed in the constructor, then the performance will degrade from O(1) to O(n) when a large number of items are added to the dictionary. As more and more items get added to the linked lists in each bucket, the lookup operations will spend most of their time traversing a linear linked list. To fix this, the buckets array has to be resized once the number of items in each bucket has gone over a certain limit. (In ConcurrentDictionary this limit is when the size of the largest bucket is greater than the number of buckets for each lock. This check is done at the end of the TryAddInternal method.) Resizing the bucket array and re-hashing everything affects every bucket in the collection. Therefore, this operation needs to take out every lock in the collection. Taking out mutiple locks at once inevitably summons the spectre of the deadlock; two threads each hold a lock, and each trying to acquire the other lock. How can we eliminate this? Simple - ensure that threads never try to 'swap' locks in this fashion. When taking out multiple locks, always take them out in the same order, and always take out all the locks you need before starting to release them. In ConcurrentDictionary, this is controlled by the AcquireLocks, AcquireAllLocks and ReleaseLocks methods. Locks are always taken out and released in the order they are in the m_locks array, and locks are all released right at the end of the method in a finally block. At this point, it's worth pointing out that the locks array is never re-assigned, even when the buckets array is increased in size. The number of locks is fixed in the constructor by the concurrencyLevel parameter. This simplifies programming the locks; you don't have to check if the locks array has changed or been re-assigned before taking out a lock object. And you can be sure that when a thread takes out a lock, another thread isn't going to re-assign the lock array. This would create a new series of lock objects, thus allowing another thread to ignore the existing locks (and any threads controlling them), breaking thread-safety. Consequences of growing the array Just because we're using locks doesn't mean that race conditions aren't a problem. We can see this by looking at the GrowTable method. The operation of this method can be boiled down to: private void GrowTable(Node[] buckets) { try { 1: Acquire first lock in the locks array // this causes any other thread trying to take out // all the locks to block because the first lock in the array // is always the one taken out first // check if another thread has already resized the buckets array // while we were waiting to acquire the first lock 2: if (buckets != m_buckets) return; 3: Calculate the new size of the backing array 4: Node[] array = new array[size]; 5: Acquire all the remaining locks 6: Re-hash the contents of the existing buckets into array 7: m_buckets = array; } finally { 8: Release all locks } } As you can see, there's already a check for a race condition at step 2, for the case when the GrowTable method is called twice in quick succession on two separate threads. One will successfully resize the buckets array (blocking the second in the meantime), when the second thread is unblocked it'll see that the array has already been resized & exit without doing anything. There is another case we need to consider; looking back at the AlterBucket method above, consider the following situation: Thread 1 calls AlterBucket; step 1 is executed to get the bucket and lock numbers. Thread 2 calls GrowTable and executes steps 1-5; thread 1 is blocked when it tries to take out the lock in step 2. Thread 2 re-hashes everything, re-assigns the buckets array, and releases all the locks (steps 6-8). Thread 1 is unblocked and continues executing, but the calculated bucket and lock numbers are no longer valid. Between calculating the correct bucket and lock number and taking out the lock, another thread has changed where everything is. Not exactly thread-safe. Well, a similar problem was solved in ConcurrentStack and ConcurrentQueue by storing a local copy of the state, doing the necessary calculations, then checking if that state is still valid. We can use a similar idea here: void AlterBucket(TKey key, ...) { while (true) { Node[] buckets = m_buckets; int bucketNo, lockNo; GetBucketAndLockNo( key.GetHashCode(), out bucketNo, out lockNo, buckets.Length); lock (m_locks[lockNo]) { // if the state has changed, go back to the start if (buckets != m_buckets) continue; Node headNode = m_buckets[bucketNo]; Mutate the node linked list as appropriate } break; } } TryGetValue and GetEnumerator And so, finally, we get onto TryGetValue and GetEnumerator. I've left these to the end because, well, they don't actually use any locks. How can this be? Whenever you change a bucket, you need to take out the corresponding lock, yes? Indeed you do. However, it is important to note that TryGetValue and GetEnumerator don't actually change anything. Just as immutable objects are, by definition, thread-safe, read-only operations don't need to take out a lock because they don't change anything. All lockless methods can happily iterate through the buckets and linked lists without worrying about locking anything. However, this does put restrictions on how the other methods operate. Because there could be another thread in the middle of reading the dictionary at any time (even if a lock is taken out), the dictionary has to be in a valid state at all times. Every change to state has to be made visible to other threads in a single atomic operation (all relevant variables are marked volatile to help with this). This restriction ensures that whatever the reading threads are doing, they never read the dictionary in an invalid state (eg items that should be in the collection temporarily removed from the linked list, or reading a node that has had it's key & value removed before the node itself has been removed from the linked list). Fortunately, all the operations needed to change the dictionary can be done in that way. Bucket resizes are made visible when the new array is assigned back to the m_buckets variable. Any additions or modifications to a node are done by creating a new node, then splicing it into the existing list using a single variable assignment. Node removals are simply done by re-assigning the node's m_next pointer. Because the dictionary can be changed by another thread during execution of the lockless methods, the GetEnumerator method is liable to return dirty reads - changes made to the dictionary after GetEnumerator was called, but before the enumeration got to that point in the dictionary. It's worth listing at this point which methods are lockless, and which take out all the locks in the dictionary to ensure they get a consistent view of the dictionary: Lockless: TryGetValue GetEnumerator The indexer getter ContainsKey Takes out every lock (lockfull?): Count IsEmpty Keys Values CopyTo ToArray Concurrent principles That covers the overall implementation of ConcurrentDictionary. I haven't even begun to scratch the surface of this sophisticated collection. That I leave to you. However, we've looked at enough to be able to extract some useful principles for concurrent programming: Partitioning When using locks, the work is partitioned into independant chunks, each with its own lock. Each partition can then be modified concurrently to other partitions. Ordered lock-taking When a method does need to control the entire collection, locks are taken and released in a fixed order to prevent deadlocks. Lockless reads Read operations that don't care about dirty reads don't take out any lock; the rest of the collection is implemented so that any reading thread always has a consistent view of the collection. That leads us to the final collection in this little series - ConcurrentBag. Lacking a non-concurrent analogy, it is quite different to any other collection in the class libraries. Prepare your thinking hats!

    Read the article

  • Elasticsearch Shard stuck in INITIALIZING state

    - by Peeyush
    I stopped one of my elastic search node & as a normal behavior elastic search started relocating my shard on that node to another node. But even after 15 hours it is still stuck in INITIALIZING state. Also that shard is fluctuating between two nodes,for some time it stays on one node then automatically shift to another node & keep on doing that after every few hours. Main issue is it is still in INITIALIZING state after so many hours. I am using version 1.2.1. This shard which is stuck, it is a replica. I am getting this error in logs: [ERROR][index.engine.internal ] [mynode] [myindex][3] failed to acquire searcher, source delete_by_query java.lang.NullPointerException [WARN ][index.engine.internal ] [mynode] [myindex][3] failed engine [deleteByQuery/shard failed on replica] [WARN ][cluster.action.shard ] [mynode] [myindex][3] sending failed shard for [myindex][3], node[Sp3URfNVQlq2i4i3EjCakw], [R], s[INITIALIZING], indexUUID [kTikCHshQMKEQ_jAuWWWnw], reason [engine failure, message [deleteByQuery/shard failed on replica][EngineException[[myindex][3] failed to acquire searcher, source delete_by_query]; nested: NullPointerException; ]]

    Read the article

  • How to use VisualStyleRenderer in Windows 7?

    - by Paulo Santos
    In a small project of mine I've came across the need of a collapsible group box. Searching the Net, I've found one here. In one of the comments there's an improvement on the original code that uses the VisualStyleRenderer class in order to acquire the TreeView open and closed glyph. Running the code it draws properly the Plus and Minus sing as Windows XP would draw it, however in Windows Vista and Windows 7 the glyph for open and closed nodes are small triangles. What kind of interface, class or PInvoke, I need to use in order to acquire the right glyph?

    Read the article

  • file path of a MenuItem target with cmdOpen action

    - by maranas
    I am trying to acquire the file path of an item within the NSMenuItem object. Using [objectname action] i am able to properly acquire the action (cmdOpen). But [objectname target] returns a null value. According to the documentation in the apple developer website, if the value is null, the action is sent to the first-responder. I want to be able to dynamically access the file path of the target file. Is there a way to do this without changing the program design?

    Read the article

  • c++ exceptions and program execution logic

    - by Andrew
    Hello everyone, I have been thru a few questions but did not find an answer. I wonder how should the exception handling be implemented in a C++ software so it is centralized and it is tracking the software progress? For example, I want to process exceptions at four stages of the program and know that exception happened at that specific stage: 1. Initialization 2. Script processing 3. Computation 4. Wrap-up. At this point, I tried this: int main (...) { ... // start logging system try { ... } catch (exception &e) { cerr << "Error: " << e.what() << endl; cerr << "Could not start the logging system. Application terminated!\n"; return -1; } catch(...) { cerr << "Unknown error occured.\n"; cerr << "Could not start the logging system. Application terminated!\n"; return -2; } // open script file and acquire data try { ... } catch (exception &e) { cerr << "Error: " << e.what() << endl; cerr << "Could not acquire input parameters. Application terminated!\n"; return -1; } catch(...) { cerr << "Unknown error occured.\n"; cerr << "Could not acquire input parameters. Application terminated!\n"; return -2; } // computation try { ... } ... This is definitely not centralized and seems stupid. Or maybe it is not a good concept at all?

    Read the article

  • iPhone Accelerometer > csv > email

    - by Bradley Powers
    Hi all, I'm trying to collect data for a machine learning project I'm working on. What I'd like to do is collect accelerometer data from an iPhone, save it to a csv and email it to myself. My app currently is able to acquire data from the accelerometer, but I'm at a bit of a loss as to how to proceed. First of all, I'd like to acquire data for a preset amount of time (after playing a sound to the user) which I don't really know how to do, and I can't find good documentation for. Also, I'd like to save that to a csv, which there is some documentation on (specifically using the NSString writeToFile method). Any recommendations/ ideas? Thanks!

    Read the article

  • SQL Server deadlock issue

    - by George2
    Hello everyone, I am using SQL Server 2008 Enterprise. I am wondering whether dead lock issue is only caused by cross dependencies (e.g. task A has lock on L1 but waits on lock on L2, and at the same time, task B has lock on L2 but waits on lock on L1)? Are there any other reasons and scenarios which will cause deadlock? Are there any other way which will causes dead lock -- e.g. timeout (a S/I/D/U statement do not return for a very long time, and deadlock error will be returned) or can not acquire lock for a long time but not caused by cross-dependencies (e.g. task C needs to get lock on table T, but another task D acquire the lock on table T without releasing the lock, which causes task C not be able to get lock on table T for a long time)? thanks in advance, George

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >