Search Results

Search found 659 results on 27 pages for 'safety'.

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

  • WCF methods sharing a dictionary

    - by YeomansLeo
    I'm creating a WCF Service Library and I have a question regarding thread-safety consuming a method inside this library, here is the full implementation that I have until now. namespace WCFConfiguration { [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Single)] public class ConfigurationService : IConfigurationService { ConcurrentDictionary<Tuple<string,string>, string> configurationDictionary = new ConcurrentDictionary<Tuple<string,string>, string>(); public void Configuration(IEnumerable<Configuration> configurationSet) { Tuple<string, string> lookupStrings; foreach (var config in configurationSet) { lookupStrings = new Tuple<string, string>(config.BoxType, config.Size); configurationDictionary.TryAdd(lookupStrings, config.RowNumber); } } public void ScanReceived(string boxType, string size, string packerId = null) { } } } Imagine that I have a 10 values in my configurationDictionary and many people want to query this dictionary consuming ScanReceived method, are those 10 values be shared for each of the clients that request ScanReceived? Do I need to change my ServiceBehavior? The Configuration method is only consumed by one person by the way.

    Read the article

  • Android threading and database locking

    - by Sena Gbeckor-Kove
    Hi, We are using AsyncTasks to access database tables and cursors. Unfortunately we are seeing occasional exceptions regarding the database being locked. E/SQLiteOpenHelper(15963): Couldn't open iviewnews.db for writing (will try read-only): E/SQLiteOpenHelper(15963): android.database.sqlite.SQLiteException: database is locked E/SQLiteOpenHelper(15963): at android.database.sqlite.SQLiteDatabase.native_setLocale(Native Method) E/SQLiteOpenHelper(15963): at android.database.sqlite.SQLiteDatabase.setLocale(SQLiteDatabase.java:1637) E/SQLiteOpenHelper(15963): at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1587) E/SQLiteOpenHelper(15963): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:638) E/SQLiteOpenHelper(15963): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:659) E/SQLiteOpenHelper(15963): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:652) E/SQLiteOpenHelper(15963): at android.app.ApplicationContext.openOrCreateDatabase(ApplicationContext.java:482) E/SQLiteOpenHelper(15963): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:193) E/SQLiteOpenHelper(15963): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:98) E/SQLiteOpenHelper(15963): at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:158) E/SQLiteOpenHelper(15963): at com.iview.android.widget.IViewNewsTopStoryWidget.initData(IViewNewsTopStoryWidget.java:73) E/SQLiteOpenHelper(15963): at com.iview.android.widget.IViewNewsTopStoryWidget.updateNewsWidgets(IViewNewsTopStoryWidget.java:121) E/SQLiteOpenHelper(15963): at com.iview.android.async.GetNewsTask.doInBackground(GetNewsTask.java:338) E/SQLiteOpenHelper(15963): at com.iview.android.async.GetNewsTask.doInBackground(GetNewsTask.java:1) E/SQLiteOpenHelper(15963): at android.os.AsyncTask$2.call(AsyncTask.java:185) E/SQLiteOpenHelper(15963): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:256) E/SQLiteOpenHelper(15963): at java.util.concurrent.FutureTask.run(FutureTask.java:122) E/SQLiteOpenHelper(15963): at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:648) E/SQLiteOpenHelper(15963): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:673) E/SQLiteOpenHelper(15963): at java.lang.Thread.run(Thread.java:1060) Does anybody have a general example for code which writes to a database from a different thread than the one reading and how can we ensure thread safety. One suggestion I've had is to use a ContentProvider, as this would handle the access of the database from multiple threads. I am going to look at this, but is this the recommended method of handling such a problem? It seems rather heavyweight considering we're talking about in front or behind Thanks in advance.

    Read the article

  • Impossible to be const-correct when combining data and it's lock?

    - by Graeme
    I've been looking at ways to combine a piece of data which will be accessed by multiple threads alongside the lock provisioned for thread-safety. I think I've got to a point where I don't think its possible to do this whilst maintaining const-correctness. Take the following class for example: template <typename TType, typename TMutex> class basic_lockable_type { public: typedef TMutex lock_type; public: template <typename... TArgs> explicit basic_lockable_type(TArgs&&... args) : TType(std::forward<TArgs...>(args)...) {} TType& data() { return data_; } const TType& data() const { return data_; } void lock() { mutex_.lock(); } void unlock() { mutex_.unlock(); } private: TType data_; mutable TMutex mutex_; }; typedef basic_lockable_type<std::vector<int>, std::mutex> vector_with_lock; In this I try to combine the data and lock, marking mutex_ as mutable. Unfortunately this isn't enough as I see it because when used, vector_with_lock would have to be marked as mutable in order for a read operation to be performed from a const function which isn't entirely correct (data_ should be mutable from a const). void print_values() const { std::lock_guard<vector_with_lock>(values_); for(const int val : values_) { std::cout << val << std::endl; } } vector_with_lock values_; Can anyone see anyway around this such that const-correctness is maintained whilst combining data and lock? Also, have I made any incorrect assumptions here?

    Read the article

  • What exactly is a reentrant function?

    - by eSKay
    Most of the times, the definition of reentrance is quoted from Wikipedia: A computer program or routine is described as reentrant if it can be safely called again before its previous invocation has been completed (i.e it can be safely executed concurrently). To be reentrant, a computer program or routine: Must hold no static (or global) non-constant data. Must not return the address to static (or global) non-constant data. Must work only on the data provided to it by the caller. Must not rely on locks to singleton resources. Must not modify its own code (unless executing in its own unique thread storage) Must not call non-reentrant computer programs or routines. How is safely defined? If a program can be safely executed concurrently, does it always mean that it is reentrant? What exactly is the common thread between the six points mentioned that I should keep in mind while checking my code for reentrant capabilities? Also, Are all recursive functions reentrant? Are all thread-safe functions reentrant? Are all recursive and thread-safe functions reentrant? While writing this question, one thing comes to mind: Are the terms like reentrance and thread safety absolute at all i.e. do they have fixed concrete definations? For, if they are not, this question is not very meaningful. Thanks!

    Read the article

  • Is locking on the requested object a bad idea?

    - by Quick Joe Smith
    Most advice on thread safety involves some variation of the following pattern: public class Thing { private static readonly object padlock = new object(); private string stuff, andNonsense; public string Stuff { get { lock (Thing.padlock) { if (this.stuff == null) this.stuff = "Threadsafe!"; } return this.stuff; } } public string AndNonsense { get { lock (Thing.padlock) { if (this.andNonsense == null) this.andNonsense = "Also threadsafe!"; } return this.andNonsense; } } // Rest of class... } In cases where the get operations are expensive and unrelated, a single locking object is unsuitable because a call to Stuff would block all calls to AndNonsense, degrading performance. And rather than create a lock object for each call, wouldn't it be better to acquire the lock on the member itself (assuming it is not something that implements SyncRoot or somesuch for that purpose? For example: public string Stuff { get { lock (this.stuff) { // Pretend that this is a very expensive operation. if (this.stuff == null) this.stuff = "Still threadsafe and good?"; } return this.stuff; } } Strangely, I have never seen this approach recommended or warned against. Am I missing something obvious?

    Read the article

  • Multiple locking task (threading)

    - by Archeg
    I need to implement the class that should perform locking mechanism in our framework. We have several threads and they are numbered 0,1,2,3.... We have a static class called ResourceHandler, that should lock these threads on given objects. The requirement is that n Lock() invokes should be realeased by m Release() invokes, where n = [0..] and m = [0..]. So no matter how many locks was performed on single object, only one Release call is enough to unlock all. Even further if o object is not locked, Release call should perform nothing. Also we need to know what objects are locked on what threads. I have this implementation: public class ResourceHandler { private readonly Dictionary<int, List<object>> _locks = new Dictionary<int, List<object>>(); public static ResourceHandler Instance {/* Singleton */} public virtual void Lock(int threadNumber, object obj) { Monitor.Enter(obj); if (!_locks.ContainsKey(threadNumber)) {_locks.Add(new List<object>());} _locks[threadNumber].Add(obj); } public virtual void Release(int threadNumber, object obj) { // Check whether we have threadN in _lock and skip if not var count = _locks[threadNumber].Count(x => x == obj); _locks[threadNumber].RemoveAll(x => x == obj); for (int i=0; i<count; i++) { Monitor.Exit(obj); } } // ..... } Actually what I am worried here about is thread-safety. I'm actually not sure, is it thread-safe or not, and it's a real pain to fix that. Am I doing the task correctly and how can I ensure that this is thread-safe?

    Read the article

  • May volatile be in user defined types to help writing thread-safe code

    - by David Rodríguez - dribeas
    I know, it has been made quite clear in a couple of questions/answers before, that volatile is related to the visible state of the c++ memory model and not to multithreading. On the other hand, this article by Alexandrescu uses the volatile keyword not as a runtime feature but rather as a compile time check to force the compiler into failing to accept code that could be not thread safe. In the article the keyword is used more like a required_thread_safety tag than the actual intended use of volatile. Is this (ab)use of volatile appropriate? What possible gotchas may be hidden in the approach? The first thing that comes to mind is added confusion: volatile is not related to thread safety, but by lack of a better tool I could accept it. Basic simplification of the article: If you declare a variable volatile, only volatile member methods can be called on it, so the compiler will block calling code to other methods. Declaring an std::vector instance as volatile will block all uses of the class. Adding a wrapper in the shape of a locking pointer that performs a const_cast to release the volatile requirement, any access through the locking pointer will be allowed. Stealing from the article: template <typename T> class LockingPtr { public: // Constructors/destructors LockingPtr(volatile T& obj, Mutex& mtx) : pObj_(const_cast<T*>(&obj)), pMtx_(&mtx) { mtx.Lock(); } ~LockingPtr() { pMtx_->Unlock(); } // Pointer behavior T& operator*() { return *pObj_; } T* operator->() { return pObj_; } private: T* pObj_; Mutex* pMtx_; LockingPtr(const LockingPtr&); LockingPtr& operator=(const LockingPtr&); }; class SyncBuf { public: void Thread1() { LockingPtr<BufT> lpBuf(buffer_, mtx_); BufT::iterator i = lpBuf->begin(); for (; i != lpBuf->end(); ++i) { // ... use *i ... } } void Thread2(); private: typedef vector<char> BufT; volatile BufT buffer_; Mutex mtx_; // controls access to buffer_ };

    Read the article

  • Microsoft Enterprise Library Caching Application Block not thread safe?!

    - by AlanR
    Good aftenoon, I created a super simple console app to test out the Enterprise Library Caching Application Block, and the behavior is blaffling. I'm hoping I screwed something that's easy to fix in the setup. Have each item expire after 5 seconds for testing purposes. Basic setup -- "every second pick a number between 0 and 2. if the cache doesn't already have it, put it in there -- otherwise just grab it from the cache. Do this inside a LOCK statement to ensure thread safety. APP.CONFIG: <configuration> <configSections> <section name="cachingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings, Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </configSections> <cachingConfiguration defaultCacheManager="Cache Manager"> <cacheManagers> <add expirationPollFrequencyInSeconds="1" maximumElementsInCacheBeforeScavenging="1000" numberToRemoveWhenScavenging="10" backingStoreName="Null Storage" type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Cache Manager" /> </cacheManagers> <backingStores> <add encryptionProviderName="" type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Null Storage" /> </backingStores> </cachingConfiguration> </configuration> C#: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Common; using Microsoft.Practices.EnterpriseLibrary.Caching; using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations; namespace ConsoleApplication1 { class Program { public static ICacheManager cache = CacheFactory.GetCacheManager("Cache Manager"); static void Main(string[] args) { while (true) { System.Threading.Thread.Sleep(1000); // sleep for one second. var key = new Random().Next(3).ToString(); string value; lock (cache) { if (!cache.Contains(key)) { cache.Add(key, key, CacheItemPriority.Normal, null, new SlidingTime(TimeSpan.FromSeconds(5))); } value = (string)cache.GetData(key); } Console.WriteLine("{0} --> '{1}'", key, value); //if (null == value) throw new Exception(); } } } } OUPUT -- How can I prevent the cache to returning nulls? 2 --> '2' 1 --> '1' 2 --> '2' 0 --> '0' 2 --> '2' 0 --> '0' 1 --> '' 0 --> '0' 1 --> '1' 2 --> '' 0 --> '0' 2 --> '2' 0 --> '0' 1 --> '' 2 --> '2' 1 --> '1' Press any key to continue . . . Thanks in advance, -Alan.

    Read the article

  • In Java Concurrency In Practice by Brian Goetz, why is the Memoizer class not annotated with @ThreadSafe?

    - by dig_dug
    Java Concurrency In Practice by Brian Goetz provides an example of a efficient scalable cache for concurrent use. The final version of the example showing the implementation for class Memoizer (pg 108) shows such a cache. I am wondering why the class is not annotated with @ThreadSafe? The client, class Factorizer, of the cache is properly annotated with @ThreadSafe. The appendix states that if a class is not annotated with either @ThreadSafe or @Immutable that it should be assumed that it isn't thread safe. Memoizer seems thread-safe though. Here is the code for Memoizer: public class Memoizer<A, V> implements Computable<A, V> { private final ConcurrentMap<A, Future<V>> cache = new ConcurrentHashMap<A, Future<V>>(); private final Computable<A, V> c; public Memoizer(Computable<A, V> c) { this.c = c; } public V compute(final A arg) throws InterruptedException { while (true) { Future<V> f = cache.get(arg); if (f == null) { Callable<V> eval = new Callable<V>() { public V call() throws InterruptedException { return c.compute(arg); } }; FutureTask<V> ft = new FutureTask<V>(eval); f = cache.putIfAbsent(arg, ft); if (f == null) { f = ft; ft.run(); } } try { return f.get(); } catch (CancellationException e) { cache.remove(arg, f); } catch (ExecutionException e) { throw launderThrowable(e.getCause()); } } } }

    Read the article

  • Java Builder pattern with Generic type bounds

    - by I82Much
    Hi all, I'm attempting to create a class with many parameters, using a Builder pattern rather than telescoping constructors. I'm doing this in the way described by Joshua Bloch's Effective Java, having private constructor on the enclosing class, and a public static Builder class. The Builder class ensures the object is in a consistent state before calling build(), at which point it delegates the construction of the enclosing object to the private constructor. Thus public class Foo { // Many variables private Foo(Builder b) { // Use all of b's variables to initialize self } public static final class Builder { public Builder(/* required variables */) { } public Builder var1(Var var) { // set it return this; } public Foo build() { return new Foo(this); } } } I then want to add type bounds to some of the variables, and thus need to parametrize the class definition. I want the bounds of the Foo class to be the same as that of the Builder class. public class Foo<Q extends Quantity> { private final Unit<Q> units; // Many variables private Foo(Builder<Q> b) { // Use all of b's variables to initialize self } public static final class Builder<Q extends Quantity> { private Unit<Q> units; public Builder(/* required variables */) { } public Builder units(Unit<Q> units) { this.units = units; return this; } public Foo build() { return new Foo<Q>(this); } } } This compiles fine, but the compiler is allowing me to do things I feel should be compiler errors. E.g. public static final Foo.Builder<Acceleration> x_Body_AccelField = new Foo.Builder<Acceleration>() .units(SI.METER) .build(); Here the units argument is not Unit<Acceleration> but Unit<Length>, but it is still accepted by the compiler. What am I doing wrong here? I want to ensure at compile time that the unit types match up correctly.

    Read the article

  • Threading Issue with WCF Service

    - by helixed
    I'm new to both WCF and threading, so please bear with me. I have a WCF service set up. The service has multiple threads, all of which act upon a single array. This works without a problem so far. However, this service has a method, which, when called, will return the array. My questions: The array is serialized when it is transferred to the client by WCF. Is this a thread safe operation? In other words, can I count on WCF to block all threads from accessing this array while it's being serialized? If I can't count on WCF to do this, then how can I implement it manually? I don't really understand how WCF would facilitate this since the serialization happens after I return from my method call. How can I guarantee a thread will not modify the array after it's been returned by my method but before WCF serializes it?

    Read the article

  • xpath query in a servlet gives exception

    - by user1401071
    I have a Document object initialized in the init() method of the servlet and use it in the doPost() method to service the requests. selectNodeList() xpath query gives exception when the servlet services many request at same time. The Exception is shown below: Caused by: javax.xml.transform.TransformerException: -1 at org.apache.xpath.XPath.execute(XPath.java:331) at org.apache.xpath.CachedXPathAPI.eval(CachedXPathAPI.java:328) at org.apache.xpath.CachedXPathAPI.selectNodeList(CachedXPathAPI.java:255) at org.apache.xpath.CachedXPathAPI.selectNodeList(CachedXPathAPI.java:235) at com.pro.bb.servlets.Controller.getDataOrPeriodForReport(Controller.java:511) ... 23 more Caused by: java.lang.ArrayIndexOutOfBoundsException: -1 at org.apache.xpath.XPathContext.pushCurrentNode(XPathContext.java:808) at org.apache.xpath.axes.PredicatedNodeTest.acceptNode(PredicatedNodeTest.java:447) at org.apache.xpath.axes.AxesWalker.nextNode(AxesWalker.java:409) at org.apache.xpath.axes.WalkingIterator.nextNode(WalkingIterator.java:176) at org.apache.xpath.axes.NodeSequence.nextNode(NodeSequence.java:320) at org.apache.xpath.axes.NodeSequence.runTo(NodeSequence.java:474) at org.apache.xpath.axes.NodeSequence.setRoot(NodeSequence.java:257) at org.apache.xpath.axes.LocPathIterator.execute(LocPathIterator.java:257) at org.apache.xpath.XPath.execute(XPath.java:308) Help me sort out the issue.

    Read the article

  • Lucene's nested query evaluation regarding negation

    - by ponzao
    Hi, I am adding Apache Lucene support to Querydsl (which offers type-safe queries for Java) and I am having problems understanding how Lucene evaluates queries especially regarding negation in nested queries. For instance the following two queries in my opinion are semantically the same, but only the first one returns results. +year:1990 -title:"Jurassic Park" +year:1990 +(-title:"Jurassic Park") The simplified object tree in the second example is shown below. query : Query clauses : ArrayList [0] : BooleanClause "MUST" occur : BooleanClause.Occur "year:1990" query : TermQuery [1] : BooleanClause "MUST" occur : BooleanClause.Occur query : BooleanQuery clauses : ArrayList [0] : BooleanClause "MUST_NOT" occur : BooleanClause.Occur "title:"Jurassic Park"" query : TermQuery Lucene's own QueryParser seems to evaluate "AND (NOT" into the same kind of object trees. Is this a bug in Lucene or have I misunderstood Lucene's query evaluation? I am happy to give more information if necessary.

    Read the article

  • Simple thread-safe non-blocking file logger class in c#

    - by Jason Renlan
    I have a web application, that will log some information to a file. I am looking for a simple thread-safe non-blocking file logger class in c#. I have little experience with threading. I known there are great logging components out there like log4Net, Enterprise Library Logging Block, ELMAH, but I do not want an external dependence for my application. I was thinking about using this queue implementation http://www.codeproject.com/KB/cpp/lockfreeq.aspx

    Read the article

  • Is Structuremap singleton thread safe?

    - by Ben
    Hi, Currently I have the following class: public class PluginManager { private static bool s_initialized; private static object s_lock = new object(); public static void Initialize() { if (!s_initialized) { lock (s_lock) { if (!s_initialized) { // initialize s_initialized = true; } } } } } The important thing here is that Initialize() should only be executed once whilst the application is running. I thought that I would refactor this into a singleton class since this would be more thread safe?: public sealed class PluginService { static PluginService() { } private static PluginService _instance = new PluginService(); public static PluginService Instance { get { return _instance; } } private bool s_initialized; public void Initialize() { if (!s_initialized) { // initialize s_initialized = true; } } } Question one, is it still necessary to have the lock here (I have removed it) since we will only ever be working on the same instance? Finally, I want to use DI and structure map to initialize my servcices so I have refactored as below: public interface IPluginService { void Initialize(); } public class NewPluginService : IPluginService { private bool s_initialized; public void Initialize() { if (!s_initialized) { // initialize s_initialized = true; } } } And in my registry: ForRequestedType<IPluginService>() .TheDefaultIsConcreteType<NewPluginService>().AsSingletons(); This works as expected (singleton returning true in the following code): var instance1 = ObjectFactory.GetInstance<IPluginService>(); var instance2 = ObjectFactory.GetInstance<IPluginService>(); bool singleton = (instance1 == instance2); So my next question, is the structure map solution as thread safe as the singleton class (second example). The only downside is that this would still allow NewPluginService to be instantiated directly (if not using structure map). Many thanks, Ben

    Read the article

  • Is this (Lock-Free) Queue Implementation Thread-Safe?

    - by Hosam Aly
    I am trying to create a lock-free queue implementation in Java, mainly for personal learning. The queue should be a general one, allowing any number of readers and/or writers concurrently. Would you please review it, and suggest any improvements/issues you find? Thank you. import java.util.concurrent.atomic.AtomicReference; public class LockFreeQueue<T> { private static class Node<E> { E value; volatile Node<E> next; Node(E value) { this.value = value; } } private AtomicReference<Node<T>> head, tail; public LockFreeQueue() { // have both head and tail point to a dummy node Node<T> dummyNode = new Node<T>(null); head = new AtomicReference<Node<T>>(dummyNode); tail = new AtomicReference<Node<T>>(dummyNode); } /** * Puts an object at the end of the queue. */ public void putObject(T value) { Node<T> newNode = new Node<T>(value); Node<T> prevTailNode = tail.getAndSet(newNode); prevTailNode.next = newNode; } /** * Gets an object from the beginning of the queue. The object is removed * from the queue. If there are no objects in the queue, returns null. */ public T getObject() { Node<T> headNode, valueNode; // move head node to the next node using atomic semantics // as long as next node is not null do { headNode = head.get(); valueNode = headNode.next; // try until the whole loop executes pseudo-atomically // (i.e. unaffected by modifications done by other threads) } while (valueNode != null && !head.compareAndSet(headNode, valueNode)); T value = (valueNode != null ? valueNode.value : null); // release the value pointed to by head, keeping the head node dummy if (valueNode != null) valueNode.value = null; return value; }

    Read the article

  • How to make Stack.Pop threadsafe

    - by user260197
    I am using the BlockingQueue code posted in this question, but realized I needed to use a Stack instead of a Queue given how my program runs. I converted it to use a Stack and renamed the class as needed. For performance I removed locking in Push, since my producer code is single threaded. My problem is how can thread working on the (now) thread safe Stack know when it is empty. Even if I add another thread safe wrapper around Count that locks on the underlying collection like Push and Pop do, I still run into the race condition that access Count and then Pop are not atomic. Possible solutions as I see them (which is preferred and am I missing any that would work better?): Consumer threads catch the InvalidOperationException thrown by Pop(). Pop() return a nullptr when _stack-Count == 0, however C++-CLI does not have the default() operator ala C#. Pop() returns a boolean and uses an output parameter to return the popped element. Here is the code I am using right now: generic <typename T> public ref class ThreadSafeStack { public: ThreadSafeStack() { _stack = gcnew Collections::Generic::Stack<T>(); } public: void Push(T element) { _stack->Push(element); } T Pop(void) { System::Threading::Monitor::Enter(_stack); try { return _stack->Pop(); } finally { System::Threading::Monitor::Exit(_stack); } } public: property int Count { int get(void) { System::Threading::Monitor::Enter(_stack); try { return _stack->Count; } finally { System::Threading::Monitor::Exit(_stack); } } } private: Collections::Generic::Stack<T> ^_stack; };

    Read the article

  • How can I implement a proper counter bean with EJB 3.0?

    - by Aaron Digulla
    I have this entity bean: import javax.persistence.*; @Entity public class CounterTest { private int id; private int counter; @Id public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCounter() { return counter; } public void setCounter(int counter) { this.counter = counter; } } and this stateful bean to increment a counter: import java.rmi.RemoteException; import javax.ejb.*; import javax.persistence.*; @Stateful public class CounterTestBean implements CounterTestRemote { @PersistenceContext(unitName = "JavaEE") EntityManager manager; public void initDB() { CounterTest ct = new CounterTest(); ct.setNr(1); ct.setWert(1); manager.persist(ct); } public boolean testCounterWithLock() { try { CounterTest ct = manager.find(CounterTest.class, 1); manager.lock(ct, LockModeType.WRITE); int wert = ct.getWert(); ct.setWert(wert + 1); manager.flush(); return true; } catch (Throwable t) { return false; } } } When I call testCounterWithLock() from three threads 500 times each, the counter gets incremented between 13 and 1279 times. How do I fix this code so that it is incremented 1500 times?

    Read the article

  • Controllers and threads

    - by user72185
    Hi, I'm seeing this code in a project and I wonder if it is safe to do: (ASP.NET MVC 2.0) class MyController { void ActionResult SomeAction() { System.Threading.Thread newThread = new System.Threading.Thread(AsyncFunc); newThread.Start(); } void AsyncFunc() { string someString = HttpContext.Request.UrlReferrer.Authority + Url.Action("Index", new { controller = "AnotherAction" } ); } } Is the controller reused, possibly changing the content of HttpContext.Request and Url, or is this fine (except for not using the thread pool). Thanks for info!

    Read the article

  • Writing re-entrant lexer with Flex

    - by Viet
    I'm newbie to flex. I'm trying to write a simple re-entrant lexer/scanner with flex. The lexer definition goes below. I get stuck with compilation errors as shown below (yyg issue): reentrant.l: /* Definitions */ digit [0-9] letter [a-zA-Z] alphanum [a-zA-Z0-9] identifier [a-zA-Z_][a-zA-Z0-9_]+ integer [0-9]+ natural [0-9]*[1-9][0-9]* decimal ([0-9]+\.|\.[0-9]+|[0-9]+\.[0-9]+) %{ #include <stdio.h> #define ECHO fwrite(yytext, yyleng, 1, yyout) int totalNums = 0; %} %option reentrant %option prefix="simpleit_" %% ^(.*)\r?\n printf("%d\t%s", yylineno++, yytext); %% /* Routines */ int yywrap(yyscan_t yyscanner) { return 1; } int main(int argc, char* argv[]) { yyscan_t yyscanner; if(argc < 2) { printf("Usage: %s fileName\n", argv[0]); return -1; } yyin = fopen(argv[1], "rb"); yylex(yyscanner); return 0; } Compilation errors: vietlq@mylappie:~/Desktop/parsers/reentrant$ gcc lex.simpleit_.c reentrant.l: In function ‘main’: reentrant.l:44: error: ‘yyg’ undeclared (first use in this function) reentrant.l:44: error: (Each undeclared identifier is reported only once reentrant.l:44: error: for each function it appears in.)

    Read the article

  • C# - Which is more efficient and thread safe? static or instant classes?

    - by Soni Ali
    Consider the following two scenarios: //Data Contract public class MyValue { } Scenario 1: Using a static helper class. public class Broker { private string[] _userRoles; public Broker(string[] userRoles) { this._userRoles = userRoles; } public MyValue[] GetValues() { return BrokerHelper.GetValues(this._userRoles); } } static class BrokerHelper { static Dictionary<string, MyValue> _values = new Dictionary<string, MyValue>(); public static MyValue[] GetValues(string[] rolesAllowed) { return FilterForRoles(_values, rolesAllowed); } } Scenario 2: Using an instance class. public class Broker { private BrokerService _service; public Broker(params string[] userRoles) { this._service = new BrokerService(userRoles); } public MyValue[] GetValues() { return _service.GetValues(); } } class BrokerService { private Dictionary<string, MyValue> _values; private string[] _userRoles; public BrokerService(string[] userRoles) { this._userRoles = userRoles; this._values = new Dictionary<string, MyValue>(); } public MyValue[] GetValues() { return FilterForRoles(_values, _userRoles); } } Which of the [Broker] scenarios will scale best if used in a web environment with about 100 different roles and over a thousand users. NOTE: Feel free to sugest any alternative approach.

    Read the article

  • Using EnterCriticalSection in Thread to update VCL label

    - by user257188
    I'm new to threads. I'm using a 3rd party library that uses threads which at times call a procedure I've provided. How do I update update a TLabel.Caption from my procedure when its called by the thread? If I've called InitializeCriticalSection elsewhere, is it as simple as EnterCriticalSection(CritSect); GlobalVariable := 'New TLabel.Caption'; LeaveCriticalSection(CritSect); And then in my main thread: EnterCriticalSection(CritSect); Label1.Caption:= 'New TLable.Caption'; LeaveCriticalSection(CritSect); But, how do I get the main thread code to be called? The thread can use SendMessage? Or is there some better/easier way (.OnIdle could check a flag set by the thread?) Thanks.

    Read the article

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