Do I need to close the Scanner in this code?
public static String input(final String out){
System.out.print(out);
java.util.Scanner sc = new Java.util.Scanner(System.in);
return sc.nextLine();
No you don't need to close it. (Not even if your IDE says you do!)
The reason you don't need to is that your code was not responsible for opening System.in. The JVM did that on startup.
The general principle is to make the code that opened a resource responsible for closing it. In this case, System.in will still be accessible to other parts of your application after the call to input returns. It may need to be used, but if you close it here, it can't be used. Calling Scanner.close() will attempt to close whatever source it is wrapping.
However, your code is (possibly) wrong for another reason. If you are going to create a Scanner for System.in, you should be doing this "globally", not in some method that could be called from lots of places.
Why?
Because you can only safely wrap a given input stream object in a Scanner once.
The Scanner takes control of the lifecycle of the stream.
The Scanner may read ahead an buffer an arbitrary number of characters from the stream making them unavailable to something else; e.g. another Scanner. So two Scanners attempting to read from the same stream can lose characters unexpectedly.
Closing the Scanner will close the wrapped source, whether you do it explicitly or via try-with-resources. However, a Scanner is not finalizable ... which means that the GC won't attempt to close the wrapped source just because a Scanner becomes unreachable.
Check with
import java.util.Scanner;
public static String input(final String out)
{
String str="";
System.out.print(out);
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
str=sc.nextLine();
}
return str;
}
Related
Hi I'm a bit uncertain about good practice within IBM DOORS Attribute DXL when it comes to which resources to release?
// I believe the following is correct for assigning the value of a buffer to an attribute of type Text.
Buffer buff = create
buff = "hello"
delete(buff)
obj.attrDXLName = tempStringOf(buff)
delete(buff)
// strings - what is required?
// eg..
string s = "hello"
s = "hello world"
s = null
// Where I am navigating through links, I may be using the following
LinkRef myLinkRef = null
myLinkRef = ...
ModName_ otherModuleHandle = data(SourceVersion myLinkRef)
Module m = ...
delete(otherModuleHandle)
In Attribute DXL, Which handles are known to need to be free'd and whats the best way to release the resource. I've seen delete(otherModuleHandle) being used, but not sure how it works or why it is needed.
I have a suspicion that DOORS DXL does some sort of reference counting in its memory model.
Any thoughts would be greatly appreciated.
I think the code listed will throw several errors?
Example- you can't refer to a buffer after calling delete on that buffer (your line 3).
If you asking about freeing up resources, that's a good practice for attribute dxl (which needs to essentially run the code for each object in the module when the module opens / the attribute is refreshed) - however, I wouldn't bother with setting strings to null. I would clean up used buffers at the end of my script, and I might close open module handles depending on what I was doing with them. On the other hand, I might leave the module handles, especially if I'm opening it multiple other times, as I have occasionally bumped into issues with code that opens / closes modules repeatedly.
I have looking at many threads about the exception "cannot pass a GCHandle across AppDomains" but I still don't get it....
I'm working with an RFID Reader which is driven by a DLL. I don't have source code for this DLL but only a sample to show how to use it.
The sample works great but I have to copy some code in another project to add the reader to the middleware Microsoft Biztalk.
The problem is that the process of Microsoft Biztalk works in another AppDomain. The reader handle events when a tag is read. But when I run it under Microsoft Biztalk I got this annoying exception.
I can't see any solution on how to make it work...
Here is some code that may be interesting :
// Let's connecting the result handlers.
// The reader calls a command-specific result handler if a command is done and the answer is ready to send.
// So let's tell the reader which functions should be called if a result is ready to send.
// result handler for reading EPCs synchronous
Reader.KSRWSetResultHandlerSyncGetEPCs(ResultHandlerSyncGetEPCs);
[...]
var readerErrorCode = Reader.KSRWSyncGetEPCs();
if (readerErrorCode == tKSRWReaderErrorCode.KSRW_REC_NoError)
{
// No error occurs while sending the command to the reader. Let's wait until the result handler was called.
if (ResultHandlerEvent.WaitOne(TimeSpan.FromSeconds(10)))
{
// The reader's work is done and the result handler was called. Let's check the result flag to make sure everything is ok.
if (_readerResultFlag == tKSRWResultFlag.KSRW_RF_NoError)
{
// The command was successfully processed by the reader.
// We'll display the result in the result handler.
}
else
{
// The command can't be proccessed by the reader. To know why check the result flag.
logger.error("Command \"KSRWSyncGetEPCs\" returns with error {0}", _readerResultFlag);
}
}
else
{
// We're getting no answer from the reader within 10 seconds.
logger.error("Command \"KSRWSyncGetEPCs\" timed out");
}
}
[...]
private static void ResultHandlerSyncGetEPCs(object sender, tKSRWResultFlag resultFlag, tKSRWExtendedResultFlag extendedResultFlag, tKSRWEPCListEntry[] epcList)
{
if (Reader == sender)
{
// Let's store the result flag in a global variable to get access from everywhere.
_readerResultFlag = resultFlag;
// Display all available epcs in the antenna field.
Console.ForegroundColor = ConsoleColor.White;
foreach (var resultListEntry in epcList)
{
handleTagEvent(resultListEntry);
}
// Let's set the event so that the calling process knows the command was processed by reader and the result is ready to get processed.
ResultHandlerEvent.Set();
}
}
You are having a problem with the gcroot<> helper class. It is used in the code that nobody can see, inside that DLL. It is frequently used by C++ code that was designed to interop with managed code, gcroot<> stores a reference to a managed object. The class uses the GCHandle type to add the reference. The GCHandle.ToIntPtr() method returns a pointer that the C++ code can store. The operation that fails is GCHandle.FromIntPtr(), used by the C++ code to recover the reference to the object.
There are two basic explanations for getting this exception:
It can be accurate. Which will happen when you initialized the code in the DLL from one AppDomain and use it in another. It isn't clear from the snippet where the Reader class object gets initialized so there are non-zero odds that this is the explanation. Be sure to keep it close to the code that uses the Reader class.
It can be caused by another bug, present in the C++ code inside the DLL. Unmanaged code often suffers from pointer bugs, the kind of bug that can accidentally overwrite memory. If that happens with the field that stores the gcroot<> object then nothing goes wrong for a while. Until the code tries to recover the object reference again. At that point the CLR notices that the corrupted pointer value no longer matches an actual object handle and generates this exception. This is certainly the hard kind of bug to solve since this happens in code you cannot fix and showing the programmer that worked on it a repro for the bug is very difficult, such memory corruption problems never repro well.
Chase bullet #1 first. There are decent odds that Biztalk runs your C# code in a separate AppDomain. And that the DLL gets loaded too soon, before or while the AppDomain is created. Something you can see with SysInternals' ProcMon. Create a repro of this by writing a little test program that creates an AppDomain and runs the test code. If that reproduces the crash then you'll have a very good way to demonstrate the issue to the RFID vendor and some hope that they'll use it and work on a fix.
Having a good working relationship with the RFID reader vendor to get to a resolution is going to be very important. That's never not a problem, always a good reason to go shopping elsewhere.
I currently have a very long running GUI-Application in QT. Later that application is going to be tested and run on an embedded device without a keyboard in full screen.
For easier debugging I have a custom assert macro, which allows me to ignore certain asserts (may include known buggy parts I have to work around for now) etc. For the time being I just print something on the console such as "Assertion: XXXX failed; abort/ignore". This is fine when I start the application within a console, but ultimately fails when I run it on the final device. In that case the assert will just block the main thread waiting for input and make the GUI hang badly without hope for recovery.
Now I am thinking about how to remedy this situation. One Idea is to just have the assert crash, as the standard assert does. But I do not really like that Idea, since there are a lot of know problems, and I've always found ignorable asserts very helpful when testing applications. Also I would have to put the messages into a separate file, so I can later see what happened while testing. Reading these files afterwards is possible, but I would prefer a simpler way to find out what went wrong.
The other idea was to make a window instead. However the asserts may be triggered in any thread and I can only create new windows in the GUI thread. Also the main event loop may be blocked by the assert, so I cannot be sure that it will handle the events correctly. I would somehow need a fully responsive stand-alone window in a separate thread, which only handles a few buttons.
Is this somehow possible in QT4?
You may post events to main thread to display dialog and wait for an answer from non-gui threads, or just display dialog if current thread is app thread
int result = -1;
if ( QTrhead::currentThread() == QCoreApplication::instance()->thread() )
{
result = AssertHandler->ShowDialog(where, what, condition);
}
else
{
QMetaObject::invokeMethod(AssertHandler, "ShowDialog", Qt::QueuedBlockingConnection, Q_RETURN_ARG(int, result), Q_ARG(QString, where), Q_ARG(QString, what), Q_ARG(QString, condition);
}
if (result != 0)
{
// handle assert
}
The AssertHandler is QObject based class with slot int ShowDialog(const QString &where, const QString what, const QString &condition). It should display dialog with assert data and buttons assert/ignore. Returns 0 when user pressed ignore, otherwise returns non zero value.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class BufferedInputOutputStreamExample
{
public static void main(String[] args) {
try{
BufferedInputStreamExample bisx=new BufferedInputStreamExample();
BufferedInputStream bis=bisx.inputMethod();
BufferedOutputStreamExample bosx=new BufferedOutputStreamExample();
bosx.outputMethod(bis);
}
catch(FileNotFoundException fnf)
{
System.out.println("Sorry--------File not exists");
}
catch(IOException io)
{
System.out.println("IOException ---:"+io.getMessage());
}
}
}
class BufferedInputStreamExample
{
BufferedInputStream bis=null;
BufferedInputStream inputMethod()throws FileNotFoundException,IOException
{
FileInputStream fin=new FileInputStream("C:/e-SDK-4.1-win32-x86_64 (1)/RahulExample/src/Test.java");
bis=new BufferedInputStream(fin);
int c;
while((c=bis.read())!=-1)
System.out.print((char)c);
System.out.println();
return bis;
}
}
class BufferedOutputStreamExample
{
BufferedOutputStream bos=null;
int outputMethod(BufferedInputStream bis)throws IOException,FileNotFoundException
{
bos=new BufferedOutputStream(new FileOutputStream("C:/varun.txt"));
int c;
while((c=bis.read())!=-1){
bos.write(c);
}
bis.close();
bos.close();
System.out.println("File created.............");
return 1;
}
}
in this program we read the content from a file by using bufferedinputstream, when i want to write the content of Test.java file in varun.txt file by using bufferedoutputstream,its create file but not write any thing in varun.txt.if we write the content from Test.java to varun.txt without reading it create file and write both.why it is done like this.
When you call bisx.inputMethod(), you're reading the stream in order to print its contents. Thing is, you don't want to do that just yet. Reading the stream consumes it, so the stream you're returning is already at its end, with nothing left to read.
If you want to print out all the contents of the file, and then write it all to the other file, that's two separate operations. Depending on the size of the file, it will require either reading the file twice -- with two different input streams -- or buffering the whole thing in memory.
Instead, if you just want to display the contents of the file as you copy it (which looks like the real goal here), you have a couple of worthwhile options...
You could have outputMethod print the data as it's writing to the output file. This is probably the simplest fix, in the short term. Of course, you'd also remove the code in inputMethod that reads the stream.
You could subclass FilterInputStream or FilterOutputStream to define a stream that, whenever it reads or writes data (respectively), does something else with it as well. It could, for example...
print the data to System.out. Very simple, but rigid. The more i consider it...meh.
copy the data to another arbitrary output stream. This would be far more flexible; for example, you could send to a log file or something. And it requires so little extra code over System.out.print, that it typically wins in the bang-for-your-buck department.
trigger an event that other objects can subscribe to. This could give you nearly unlimited flexibility (as the subscribers are no longer forced to care about streams), but can also be quite a bit more complex. (You'd basically need to add an event/subscription API.) It'd typically be overkill for a tiny project like this one.
Note that if you go this route, you should consider refactoring things so that the objects' constructors take a stream rather than creating one. That way, main can decide whether the output happens and where it goes, and the other objects don't even have to care. They can just do their job, treating the streams as regular old InputStreams and OutputStreams, and the stream you pass in determines what else happens.
(By the way: In order to concentrate on the main issue, i've semi-ignored the fact that you're "decoding" by casting to char. This may not faithfully reproduce the contents of the file, unless you know for a fact that the contents are ASCII characters. I assume the output is a debugging thing, so this doesn't deserve a long rant...but know that in the general case, it is likely to cause issues.)
I have a weird problem regarding the use of threads inside a Firebreath plugin (in this case a FB plugin, but could happen anywhere); I will try to explain:
1) My plugin creates a thread (static), and it receives a pointer to "this" every time it gets added to a page.
2) So, now I have a thread with a pointer to the plugin, so I can call it's methods.
3) Very nice so far, BUT, suppose that I have a button (coded in HTML), which when pressed will REMOVE the current plugin, put in place another one and launch another thread.
I have described my scenario, now for the problem, when a plugin gets added it launches a thread; inside the thread there is a pointer to "this". First time, it gets fired...while the thread is executing I press the HTML button (so, the current plugin now is destroyed) and a new one is placed. The thread from the 1st plugin ends, and now returns...but it returns to the 2nd instance of the plugin.
The plugin is an image viewer, the first plugin look for a picture, it gets removed and a new one is placed; BUT the image from the 1st plugin is placed in the 2nd one. I don't know where to start looking, apparently the pointer has an address to the plugin (e.g. 12345), the plugin gets removed and instantiated again with the same memory address (12345).
Is there some way to avoid that behavior?
This is the code I have so far:
myPlugin.h
unsigned ThreadId;
HANDLE hThread;
myPlugin.cpp
unsigned __stdcall myPlugin::Thread(void *data)
{
myPlugin* this = (myPlugin*) data;
this->getImage("http:\\host.com\\image.jpg");
_endthreadex(0); //EDIT: addedd this missing line to end the thread
}
void myPlugin::onPluginReady(std::string imageUrl)
{
hThread = (HANDLE)_beginthreadex(NULL, 0, myPlugin::Thread, (void*) **this**, 0, &ThreadId);
}
void myPlugin::getImage()
{
//get an image using CURL... //no problem here
}
You need to stop and join the thread in the shutdown() function of your Plugin class; that will be called before things are actually unloaded and that will help avoid the problem.
I would also recommend using boost::thread, since FireBreath already compiles it all in, and that will help simplify some of this; you can hold a weak_ptr in your thread to the plugin class rather than passing in a void*. Of course, either way you'll need to stop and join the thread during the plugin shutdown (and the thread needs to stop quickly or the browser will get cranky about it taking so long).