ConcurrentModificationException in Android while accessing Shared Preferences - exception

When I develop an android app, I run into the exception which I do not have any clue; I have googled related topics but none of them helped.
Fatal Exception: java.util.ConcurrentModificationException
java.util.HashMap$HashIterator.nextEntry (HashMap.java:806)
java.util.HashMap$KeyIterator.next (HashMap.java:833)
com.android.internal.util.XmlUtils.writeSetXml (XmlUtils.java:298)
com.android.internal.util.XmlUtils.writeValueXml (XmlUtils.java:447)
com.android.internal.util.XmlUtils.writeMapXml (XmlUtils.java:241)
com.android.internal.util.XmlUtils.writeMapXml (XmlUtils.java:181)
android.app.SharedPreferencesImpl.writeToFile (SharedPreferencesImpl.java:596)
android.app.SharedPreferencesImpl.access$800 (SharedPreferencesImpl.java:52)
android.app.SharedPreferencesImpl$2.run (SharedPreferencesImpl.java:511)
java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1112)
java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:587)
java.lang.Thread.run (Thread.java:841)

Preferences are thread safe(!), but not process safe. The answer of
#mohan mishra simply not true, no need to synchronize everything. The problem here, as statet out in another question is, that per documentation you MUST NOT modify any instance that is returned by getStringSet and getAll
getStringSet()
Note that you must not modify the set instance returned by this call.
The consistency of the stored data is not guaranteed if you do, nor is
your ability to modify the instance at all.
getAll()
Note that you must not modify the collection returned by this method,
or alter any of its contents. The consistency of your stored data is
not guaranteed if you do.
To the other question
Documentation

Please ensure that you are not accessing the preferences from any type of background thread. Also all your methods to add to preference must be synchronised(if you have your own preference managing class)

Related

How to throw an exception in Azure Logic Apps?

Is it possible to throw an exception in a Logic App?
Specifically, I'm trying to throw an exception inside of a scope. Then in the run after of the scope I'd check if it failed and inspect it for errors. I tried using a terminate inside of a scope, but that terminates the entire logic app run.
As an updated solution we can use Terminate control, Terminate control has 3 status: Failed, Canceled, and Succeeded.
Quick Answer (TL;DR)
Problem: MSFT Azure logic app throwing exceptions
Workaround: Use logic app Scope element to simulate throwing exceptions
Create a scope element to use as your "try-catch" block
Force the scope element to fail with an invalid command to simulate an exception
Allow the scope element to fail naturally and that will count as an exception too
Detailed Answer
Context
MSFT Azure logic app workflows
live version as of 2020-06-14
Problem
Scenario: Developer wishes to throw an exception or use try-catch semantics in a logic app
Solution
As of this writing, the live version of the product does not support this feature. There is a workaround.
Workaround
Use logic app scope element
add a conditional statement inside the scope element
If the conditional statement meets the failure condition, force an exception with a deliberately invalid command
for example create a variable assignment with the value int('__ERROR__')
If the conditional statement does not meet the failure condition, do nothing
The rest of the logic app consists of two paths
The first path runs on the success of the scope element
The second path runs on the failure of the scope element (failed, skipped, timed out)
Example
Create a scope element as a "try-catch" block
Create a variable compose element with an invalid command
int('__ERROR__') ## this will cause the enclosing scope to fail
## the string __ERROR__ cannot be cast to integer
Respond to exit status of the Scope element enclosing your exception
See also
related SO answer about forcing exceptions https://stackoverflow.com/a/61101945/42223
No, there is no Action or Connector directly analogous to something like a throw in C#.
The closest you can get right now would be to do something like use another LogicApp instead of a scope from which you can return a specific status code.
It seems like there still is no option for this inside Logic App or its little brother Power Automate / Microsoft Flow.
The way I have come up with and have used in some flows, is I simply add an action for something I know for a fact will fail.
The simplest (and probably the cheapest as the built-in actions cost less in Logic Apps, even if we are talking fractions of a dollar here either way) is probably to initialize a variable, e.g. called ThrowException with type of integer.
Then a "Set variable" action is added wherever I want my flow to fail, where I set the value (remember it is of type integer) to any string expression. I simply use the expression string('Exception').
Simple example screenshot
Since the value is set via an expression this is still a valid template, but will fail upon runtime when the value is actually being set.
After this, simply use parallel branches, with appropriate Run After settings, as usual.

Delete the backing Lambda function for a Lambda-backed custom resource

I have an AWS CloudFormation template that creates an OpsWorks stack and deploys an application. To deploy the application, I am using a Lambda function and a custom resource which utilizes that function. My problem is: that Lambda function will only be executed one time during the creation of the stack, and then it will never be used again. Is there any way to delete the Lambda function by AWS CloudFormation at the end of the execution of the stack?
First, I should say Aditya is right, you shouldn't delete the backing Lambda as it's used throughout the lifecycle.
However, if you really really want to do it, one way is to simply have the function delete itself (and related resources, eg, role) after running.
that Lambda function will only be executed one time during the
creation of the stack, and then it will never be used again.
^^That's not the case. The backing Lambda function for a Lambda-backed custom resource will be invoked everytime the corresponding resource is touched (i.e. created, updated or deleted). AWS CloudFormation will pass RequestType parameter to that function everytime it sees that the resource is being touched, and pass it one of these values: Create, Update, Delete. Your Lambda function should perform the necessary action taking that param into account. Based on your question it appears that your Lambda function only caters to RequestType = Create?
Also, as per AWS docs, you won't be charged for creating a Lambda function, but only if you actually invoke it. So cost can't be deterring factor for keeping the function around.
On the contrary, if your concern is that you don't want extra clutter, you can try creating a common CloudFormation stack who's job will be to create shared resources, and you can then define that Lambda function over there? I'll have to know about your entire workflow to say for sure if that approach will work or not.
For what it's worth, I'd recommend not deleting the backing function of the Lambda-backed custom resource because it'll be a pain when someone touches the corresponding resource in the future, or wants to create another instance of the same resource type.
Some of your assumptions regarding custom resources are not true. In a Lambda backed custom resource, you implement your logic to support creation, update and deletion of the resource. These indications are sent from CloudFormation via the event and give you information about the stack process.
It’s important to understand the custom resource life cycle, to prevent your data from being deleted.
Create - that’s easy, when a resource is being created an event with request type Create is sent to your function.
Delete - this one is more tricky. When a resource is being deleted a Delete request type is sent. But there are more scenarios other than resource Delete. We will have to explain Update first.
Update - gets called if any of your custom resource properties were changed. For example, in our app we can modify the allowed callback urls, which will trigger the function with an Update request type
I welcome you to read more about best practices in creating custom resources in this blog post

cfthrow is this how you use it? (from Adobe's doc)

I was reading the documentation for cfthrow and came accross this
When to use the cfthrow tag
Use the cfthrow tag when your application can identify and handle
application-specific errors. One typical use for the cfthrow tag is in
implementing custom data validation. The cfthrow tag is also useful
for throwing errors from a custom tag page to the calling page.
For example, on a form action page or custom tag used to set a
password, the application can determine whether the password entered
is a minimum length, or contains both letters and number, and throw an
error with a message that indicates the password rule that was broken.
The cfcatch block handles the error and tells the user how to correct
the problem.
Have I been doing it wrong all this time or is this just a terrible use-case?
I was taught that exceptions shouldn't be used to handle regular application flow but for stuff that is somewhat out of your control. For example, a file being locked when you go to write to it.
A user breaking a password rule doesn't quite sound like something that's out of your control.
That is a poor example not a poor use case. I personally would pass in the parameters to a validation function and return a result that contained a pass or fail and a collection of failure messages to display to the user.
How I use exceptions is as follows.
Within functions. Let's say that you have a function that you are getting some data from the database and you are then constructing a structure from it. If the query returned has no values you have several options:-
You could return an empty structure and let the calling code deduce the problem from the fact the structure is empty. This is not ideal because then the application has to have complicated logic to address the missing data.
You could return a more complex datatype where one property is whether the process went ok and the actual data. Again this is not optimal as you have to then make this access the property on every call when the majority of the time you have data and again your application is dealing with this issue.
Or you could raise a custom exception with cfthrow indicating that there is no record that matches. This then means that you can choose to ignore the prospect of this error happening and let it bubble up to the onError handler or you could surround it in a try catch statement and deal with it there and then. This keeps your API clean and sensible.
Wrapping external errors let's say that you connect to an external API using cfhttp over https. Now this requires installing the certificate in your keystore otherwise it throws an error. If this certificate gets updated then it will start erroring again. In this instance I would wrap the call in a try catch and should this be the error I would wrap that in my own custom exception with a message detailing that we need to update the cert in the keystore so that any developer debugging it knows what to do to fix it without having to work it out. If it is not that particular error then I would cfrethrow it so that it bubbles up and is dealt with by whatever exception handling logic is above the call.
These are just a few examples, but there are more. To summarise I would say that throwing exceptions is a way of communicating up through the tiers of an application when something has occurred that is not the hoped for behaviour while keeping your API/Application logic clean and understandable.
It's really up to your discretion. It's extremely common in many languages to use exceptions for everything, including input validation.
Importantly, exceptions have nothing to do with something being in your control or not. For example, suppose that you have a fairly long and complicated module that uploads a file. There are many fail points in something like that: the file could be too big, the file could be the wrong format, etc. Without exceptions your only option is a lot of if/then checks and some kind of status return at the very end. With exceptions, all you have to do is use a set of cfthrows:
<cfthrow type="FileUpload.TooBig" message="The file size was #FileSize#, but the maximum size allowed is #MaxFileSize#">
<cfthrow type="FileUpload.WrongType" message="The file type was #FilType#, but the accepted types are #AcceptedTypeList#">
Then, whatever is calling the file upload function can catch either with <cfcatch type="FileUpload"> or catch a specific one (e.g. <cfcatch type="FileUpload.WrongType">).
Also, technically a user breaking a password is out of your control, in the sense that the user has determined the value for the password. That said, I loathe password rules as invariably they make it harder, not easier, to maintain security.

Graceful failure in Labview (after failed opening of device - in this case camera)

I was wondering how to make it so the rest of the program runs when one component fails to (and therefor the rest of the path that relied on this component is incapacitated as well). In other languages, this is equivalent to "catching an exception," but the added issue here is that I'm afraid that even if such a feature existed (cant find if it does), then the rest of the program would still try to run... Any advice would be very much appreciated. Thanks in advance!
LabVIEW doesn't have exception handling, but handles error in a different way: (nearly) all VIs accept an error cluster as input (and so should yours); if it is positive (an error occurred), the VI will return immediately, passing error as output, and next will get it as input, etc. This is called error.
As all these VIs transmit this cluster between each others you will get it in your top-level VI, so if error occurs you just have to cleanup stuff correctly it and exit.

MEF: "Unable to load one or more of the requested types. Retrieve the LoaderExceptions for more information"

Scenario: I am using Managed Extensibility Framework to load plugins (exports) at runtime based on an interface contract defined in a separate dll. In my Visual Studio solution, I have 3 different projects: The host application, a class library (defining the interface - "IPlugin") and another class library implementing the interface (the export - "MyPlugin.dll").
The host looks for exports in its own root directory, so during testing, I build the whole solution and copy Plugin.dll from the Plugin class library bin/release folder to the host's debug directory so that the host's DirectoryCatalog will find it and be able to add it to the CompositionContainer. Plugin.dll is not automatically copied after each rebuild, so I do that manually each time I've made changes to the contract/implementation.
However, a couple of times I've run the host application without having copied (an updated) Plugin.dll first, and it has thrown an exception during composition:
Unable to load one or more of the requested types. Retrieve the LoaderExceptions for more information
This is of course due to the fact that the Plugin.dll it's trying to import from implements a different version of IPlugin, where the property/method signatures don't match. Although it's easy to avoid this in a controlled and monitored environment, by simply avoiding (duh) obsolete IPlugin implementations in the plugin folder, I cannot rely on such assumptions in the production environment, where legacy plugins could be encountered.
The problem is that this exception effectively botches the whole Compose action and no exports are imported. I would have preferred that the mismatching IPlugin implementations are simply ignored, so that other exports in the catalog(s), implementing the correct version of IPlugin, are still imported.
Is there a way to accomplish this? I'm thinking either of several potential options:
There is a flag to set on the CompositionContainer ("ignore failing imports") prior to or when calling Compose
There is a similar flag to specify on the <ImportMany()> attribute
There is a way to "hook" on to the iteration process underlying Compose(), and be able to deal with each (failed) import individually
Using strong name signing to somehow only look for imports implementing the current version of IPlugin
Ideas?
I have also run into a similar problem.
If you are sure that you want to ignore such "bad" assemblies, then the solution is to call AssemblyCatalog.Parts.ToArray() right after creating each assembly catalog. This will trigger the ReflectionTypeLoadException which you mention. You then have a chance to catch the exception and ignore the bad assembly.
When you have created AssemblyCatalog objects for all the "good" assemblies, you can aggregate them in an AggregateCatalog and pass that to the CompositionContainer constructor.
This issue can be caused by several factors (any exceptions on the loaded assemblies), like the exception says, look at the ExceptionLoader to (hopefully) get some idea
Another problem/solution that I found, is when using DirectoryCatalog, if you don't specify the second parameter "searchPattern", MEF will load ALL the dlls in that folder (including third party), and start looking for export types, that can also cause this issue, a solution is to have a convention name on all the assemblies that export types, and specify that in the DirectoryCatalog constructor, I use *_Plugin.dll, that way MEF will only load assemblies that contain exported types
In my case MEF was loading a NHibernate dll and throwing some assembly version error on the LoaderException (this error can happen with any of the dlls in the directory), this approach solved the problem
Here is an example of above mentioned methods:
var di = new DirectoryInfo(Server.MapPath("../../bin/"));
if (!di.Exists) throw new Exception("Folder not exists: " + di.FullName);
var dlls = di.GetFileSystemInfos("*.dll");
AggregateCatalog agc = new AggregateCatalog();
foreach (var fi in dlls)
{
try
{
var ac = new AssemblyCatalog(Assembly.LoadFile(fi.FullName));
var parts = ac.Parts.ToArray(); // throws ReflectionTypeLoadException
agc.Catalogs.Add(ac);
}
catch (ReflectionTypeLoadException ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
}
CompositionContainer cc = new CompositionContainer(agc);
_providers = cc.GetExports<IDataExchangeProvider>();