Checking the version of JRE used during run-time - version

I have multiple version of jre's installed on my system. Is there any way i would know which JRE version is being used by the application during run time.
There might be possible that application may use lower version of JRE -"Not Sure"
Thanks in Advance.

Using
System.getProperty("java.version")
will return the version of the currently running JVM.
Sometimes this does not return anything (don't know why). In that case you can try:
System.getProperty("java.runtime.version");

Like a_horse_with_no_name said: you can do this by calling System.getProperty("java.version").
If you need this information to make sure that the program is started using the correct JVM version, then try this:
public class Version
{
//specifies minimum major version. Examples: 5 (JRE 5), 6 (JRE 6), 7 (JRE 7) etc.
private static final int MAJOR_VERSION = 7;
//specifies minimum minor version. Examples: 12 (JRE 6u12), 23 (JRE 6u23), 2 (JRE 7u2) etc.
private static final int MINOR_VERSION = 1;
//checks if the version of the currently running JVM is bigger than
//the minimum version required to run this program.
//returns true if it's ok, false otherwise
private static boolean isOKJVMVersion()
{
//get the JVM version
String version = System.getProperty("java.version");
//extract the major version from it
int sys_major_version = Integer.parseInt(String.valueOf(version.charAt (2)));
//if the major version is too low (unlikely !!), it's not good
if (sys_major_version < MAJOR_VERSION) {
return false;
} else if (sys_major_version > MAJOR_VERSION) {
return true;
} else {
//find the underline ( "_" ) in the version string
int underlinepos = version.lastIndexOf("_");
try {
//everything after the underline is the minor version.
//extract that
int mv = Integer.parseInt(version.substring(underlinepos + 1));
//if the minor version passes, wonderful
return (mv >= MINOR_VERSION);
} catch (NumberFormatException e) {
//if it's not ok, then the version is probably not good
return false;
}
}
}
public static void main(String[] args)
{
//check if the minimum version is ok
if (! isOKJVMVersion()) {
//display an error message
//or quit program
//or... something...
}
}
}
All you have to do is change MAJOR_VERSION and MINOR_VERSION to the values that you want and recompile. I use it in my programs all the time and it works well. Warning: it doesn't work if you change System.getProperty("java.version") with System.getProperty("java.runtime.version")... the output is slightly different.

You can put this into static code of a class so it runs only once:
(This code is not mine. You can refer here:- Getting Java version at runtime
public static double JAVA_VERSION = getVersion ();
public static double getVersion () {
String version = System.getProperty("java.version");
int pos = version.indexOf('.');
pos = version.indexOf('.', pos+1);
return Double.parseDouble (version.substring (0, pos));
}
And if that does not turn up..
String version = Runtime.class.getPackage().getImplementationVersion()
Other links you can refer:
http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html
http://docs.oracle.com/javase/1.5.0/docs/relnotes/version-5.0.html

tl;dr
Runtime.version().toString()
See this code run at Ideone.com.
12.0.1+12
Java 9+
The other Answers here are outdated as of Java 9 and Java 10.
Runtime.Version class
👉 Java 9 gained a class dedicated to representing the version of Java: Runtime.Version.
To get an instance of that class, use the version method added to the pre-existing class Runtime.
Runtime.Version v = Runtime.version() ;
From there you interrogate the various pieces of version information.
// Required parts.
int feature = v.feature() ;
int interim = v.interim() ;
int update = v.update() ;
int patch = v.patch() ;
// Optional parts.
Optional<Integer> build = v.build() ;
Optional<String> pre = v.pre() ;
Optional<String> optional = v.optional() ;
See this code run at Ideone.com:
feature: 12
interim: 0
update: 1
patch: 0
build: Optional[12]
pre: Optional.empty
optional: Optional.empty
Note that major, minor, and security are deprecated as of Java 10. Version numbering in Java was redefined in Java 10 and later. To quote the Javadoc:
The sequence may be of arbitrary length but the first four elements are assigned specific meanings, as follows:
$FEATURE.$INTERIM.$UPDATE.$PATCH
$FEATURE — The feature-release counter, incremented for every feature release regardless of release content. Features may be added in a feature release; they may also be removed, if advance notice was given at least one feature release ahead of time. Incompatible changes may be made when justified.
$INTERIM — The interim-release counter, incremented for non-feature releases that contain compatible bug fixes and enhancements but no incompatible changes, no feature removals, and no changes to standard APIs.
$UPDATE — The update-release counter, incremented for compatible update releases that fix security issues, regressions, and bugs in newer features.
$PATCH — The emergency patch-release counter, incremented only when it's necessary to produce an emergency release to fix a critical issue.
The fifth and later elements of a version number are free for use by platform implementors, to identify implementor-specific patch releases.
FYI, Wikipedia maintains a history of Java versions. The Long-Term Support versions are 8, 11, and 17.

Related

Why calling `free(malloc(8))`?

The Objective-C runtime's hashtable2.mm file contains the following code:
static void bootstrap (void) {
free(malloc(8));
prototypes = ALLOCTABLE (DEFAULT_ZONE);
prototypes->prototype = &protoPrototype;
prototypes->count = 1;
prototypes->nbBuckets = 1; /* has to be 1 so that the right bucket is 0 */
prototypes->buckets = ALLOCBUCKETS(DEFAULT_ZONE, 1);
prototypes->info = NULL;
((HashBucket *) prototypes->buckets)[0].count = 1;
((HashBucket *) prototypes->buckets)[0].elements.one = &protoPrototype;
};
Why does it allocate and release the 8-bytes space immediately?
Another source of confusion is this method from objc-os.h:
static __inline void *malloc_zone_malloc(malloc_zone_t z, size_t size) { return malloc(size); }
While it uses only one parameter, does the signature ask for two?
For the first question I can only assume. My bet it was done to avoid/reduce memory churn, or segment the memory for some other reason. You can briefly find where it's discussed in the Changelog of bmalloc (which is not quite relevant, but i could not find a better reference):
2017-06-02 Geoffrey Garen <ggaren#apple.com>
...
Updated for new APIs. Note that we cache one free chunk per page
class. This avoids churn in the large allocator when you
free(malloc(X))
It's unclear however, if the memory churn is caused by this technique or it was supposed to address it.
For the second question, Objective-C runtime used to work with "zones" in order to destroy all allocated variables by just destroying the said zone, but it proved being error prone and later it was agreed to not use it anymore. The API, however still uses it for historical reasons (backward compatibility, i assume), but says that zones are ignored:
Zones are ignored on iOS and 64-bit runtime on OS X. You should not use zones in current development.

Media Foundation : Looping video unstable on 6th run

Took current media foundation sample from github (MF_ProtectedPlayback, but could have been one of the others).
Added the following so it loops when it gets to the end :
CPlayer::HandleEvent()
{
case MEEndOfPresentation:
CHECK_HR(hr = OnPresentationEnded(pEvent));
// ADV_SW: Loop.
{
static DWORD dbg_count = 0;
dbg_count++;
char title[100];
sprintf_s(title, "Loop: %d", dbg_count);
SetWindowTextA(m_hwndEvent, title);
}
Play();
break;
}
Also, in CPlayer::StartPlayback
... modified so second play starts from beginning
// Start from beginning
PROPVARIANT varStart = { 0 };
InitPropVariantFromInt64(0, &varStart);
hr = m_pSession->Start(&GUID_NULL, &varStart);
When I play example file http://advance-software.com/misc/ad.mp4 (download & run locally)
It works fine for first 5 loops, then starts breaking up on the 6th.
Anyone know what's up ?
Thanks in advance,
Steve.
Seems you must call
m_pSession->Stop();
before the Start() when looping to ensure stability.
Surprised this doesn't occur internally if a requirement to ensure API robustness but such are the dark arts of Media Foundation :)

Sorting list of files in android throwing 'Comparison method violates its general contract!'

It's happening on my Android application & here is the stack trace:
Caused by java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeHi(TimSort.java:864)
at java.util.TimSort.mergeAt(TimSort.java:481)
at java.util.TimSort.mergeForceCollapse(TimSort.java:422)
at java.util.TimSort.sort(TimSort.java:219)
at java.util.TimSort.sort(TimSort.java:169)
at java.util.Arrays.sort(Arrays.java:2023)
at java.util.Collections.sort(Collections.java:1883)
Here is my sort logic:
private static void sortFiles(List<File> listFiles, int sortDirection) {
try {
if (sortDirection == sortLatestFirst) {
Collections.sort(listFiles, new LatestFirstComparator());
...
Here is the comparator:
class LatestFirstComparator implements Comparator<File> {
#Override
public int compare(File f1, File f2) {
return Long.compare(f2.lastModified(), f1.lastModified());
}
}
I've found related questions & other solutions, but none of them solves my problem.
Moreover, this is not a consistent behavior, but happening only with some of the app users.
As said by others, the problem lies in the fact that the value of the last modified timestamp can change during the sort operation. In order to sort reliably, you have to cache the values for the duration of the sort operation:
private static void sortFiles(List<File> listFiles, int sortDirection) {
if(listFiles.isEmpty()) return;
Map<File,Long> cache = new HashMap<>();
Comparator<File> byTime
= Comparator.comparing(f -> cache.computeIfAbsent(f, File::lastModified));
if(sortDirection == sortLatestFirst) byTime = byTime.reversed();
listFiles.sort(byTime);
}
I assume that you use a notification mechanism for changes anyway, to decide when to reload the file list, so the sorting operation does not need to deal with it.
If you want to support an API level that doesn’t support Java 8 features, you have to use the more verbose variant
private static void sortFiles(List<File> listFiles, int sortDirection) {
if(listFiles.isEmpty()) return;
final Map<File,Long> cache = new HashMap<File,Long>();
Comparator<File> byTime = new Comparator<File>() {
#Override
public int compare(File f1, File f2) {
Long t1 = cache.get(f1), t2 = cache.get(f2);
if(t1 == null) cache.put(f1, t1 = f1.lastModified());
if(t2 == null) cache.put(f2, t2 = f2.lastModified());
return t1.compareTo(t2);
}
};
if(sortDirection == sortLatestFirst) byTime = Collections.reverseOrder(byTime);
Collections.sort(listFiles, byTime);
}
EDIT: Following an advice from the comment by User Holger I'm expanding the answer by adding here important points from my previous comments. They are put in quotation blocks.
As I pointed out in comments, most probably some of the files being sorted are modified during the sorting. Then, what was initially an old file becomes a new file during sorting:
e.g. file A is detected as newer than B, and B newer than C, but then C is modified and appears newer than A
Thus the ordering relation 'is newer' appears non-transitive, which breaks the contract; hence the error.
If you need stable data, I suppose you could make your own objects with copies of necessary attributes; then the ordering will be well-defined, but... the final order may appear obsolete if files are modified during sorting. Anyway you can't avoid that in a multitasking environment; you'll never know when some other thread or process creates, modifies or deletes files until you re-scan the directory
IMHO you can only write your own sorting routine, which would handle such non-transitivity safely. For example it can reiterate when it detects the situation. But take care not to iterate too many times - if two or more files get updated constantly, the re-sorting routine could never finish its work!

Strange "memory" behaviour on AWS Lambda using with Node and Node-gyp

I have an AWS Lambda written in NodeJS the invocation process is pretty straightforward
NODEJS -> NodeModule(CPP) -> Extern C Function, this setup is compiled with node-gyp.
You can see the entire code here at https://drive.google.com/open?id=0B-2d-CuY5fkwS3lwdE96R1V6NEk
The CPP node module invokes a function in C, that runs a loop. and increments two variables one in the scope of the C function and the other in main scope of the C code.
When you run this code locally. The loop increments and both the variables reach 11, as expected how much ever you run it. But when you run this same code in AWS Lambda, there is some sort of "memory" for each invocation. And the variable in the general scope, which is not getting reset is increasing, in multiples of 11, 22, 33 etc.
To repeat, this never happens locally, both the variables are always at 11.
you can build by running
1. node-gyp clean configure build
2. node app.js ( for local running)
Index.js is for AWS Lambda
I really cant explain this behavior? is there some sort of context or some sort of "memory" or caching that is available with Lambda?
I have made an Open API gateway for the same. (Feel free to refresh and see the "memory" in action).
https://koj2yva6z9.execute-api.us-east-1.amazonaws.com/dev/testLambdaCache
This behavior is sometimes inconsistent, sometimes the count resets. Or you can reset by uploading new AWS lambda code.
Any thoughts on this strange behavior is appreciated.
app.js (used for local testing)
var addon = require('./build/Release/addon');
console.log(addon.testCache());
console.log(" addon method completed");
index.js (used in lambda)
console.log('Loading function');
exports.handler = (event, context, callback) => {
var addon = require('./build/Release/addon');
var returnvalue=addon.testCache();
console.log(returnvalue);
console.log(" addon method completed");
callback(null, "success::"+returnvalue);
}
base.cc (wrapper for C code)
#include <node.h>
#include <iostream>
#include <stdlib.h>
#include<string>
#include<cstring>
using namespace std;
extern "C" char* testCache();
namespace demo {
using v8::FunctionCallbackInfo;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
using v8::Exception;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
cout << "C++ method started\n";
char *returnStrings=NULL;
returnStrings= testCache();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, returnStrings ));
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "testCache", Method);
}
NODE_MODULE(addon, init)
}
decoder.c (c code running the loop)
int tmpCounter=0;
char* testCache()
{
int counter=0;
printf("Local counter --> %d Global Counter --> %d\n",counter,tmpCounter);
for(int i=0;i <10; i++)
{
counter = counter +1;
tmpCounter = tmpCounter +1;
//sleep(1);
}
printf("Local counter --> %d Global Counter --> %d\n",counter,tmpCounter);
counter=counter+1;
tmpCounter=tmpCounter+1;
char strCounter[100];
char strTmpCounter[100];
snprintf(strCounter, 16, "%d", counter);
snprintf(strTmpCounter, 16, "%d", tmpCounter);
char *returnString=NULL;
returnString=malloc(1000);
strcat(returnString, "Count:");
strcat(returnString, strCounter);
strcat(returnString, " TmpCount:");
strcat(returnString, strTmpCounter);
strcat(returnString, "\0");
printf("%s\n",returnString);
fflush(stdout);
return returnString;
}
is there some sort of context or some sort of "memory" or caching that is available with Lambda?
I wouldn't say it's "available," in the sense that it is predictable or consistent, because you should not design around it, but yes, there is container reuse.
To see this in action:
Create a uuid, or random number, or something like that, and store it in a global variable outside your handler. Then, inside the handler, log it. You'll see that the same process or group of processes (as identified by the uuid) will likely, but not necessarily, handle subsequent requests that are close together in time.
Let’s say your function finishes, and some time passes, then you call it again. Lambda may create a new container all over again [...]
However, if you haven’t changed the code and not too much time has gone by, Lambda may reuse the previous container. This offers some performance advantages to both parties: Lambda gets to skip the nodejs language initialization, and you get to skip initialization in your code. Files that you wrote to /tmp last time around will still be there if the sandbox gets reused.
https://aws.amazon.com/blogs/compute/container-reuse-in-lambda/
All call to strcat into testCache are UB because of mallocated memory is not inited.
Change it using calloc
returnString=calloc(1, 1000);
or change the first one with sprintf
sprintf(returnString, "Count:");
Moreover strcat(returnString, "\0"); is useless
Finally always check malloc & friend returned value, e.g.
if (returnString != NULL)
{
// OK, MEMORY ALLOCATED
}
else
{
// ERROR
}

How to determine Windows version in future-proof way

I noticed that GetVersionEx() is declared deprecated. Worse yet, for Windows 8.1 (and presumably future releases) the version number is limited by the application manifest.
My goal is to collect analytics on operating systems which the users are running, so I can appropriately target support. I would like a future-proof solution for collecting this data. Updating the manifest won't work because I can only update the manifest for Windows versions which have already been released, not for future versions. The suggested replacement API, the version helper functions, is useless.
How can I collect the actual Windows version number?
To clarify: By "future proofing", I just mean that I want something that has a reasonably good chance of working on the next version of Windows. Nothing is certain, but the docs do say that GetVersionEx() won't work.
MSDN has an example showing how to use the (useless for your scenario) version helper functions, but in the introduction is the following:
To obtain the full version number for the operating system, call the GetFileVersionInfo function on one of the system DLLs, such as Kernel32.dll, then call VerQueryValue to obtain the \StringFileInfo\\ProductVersion subblock of the file version information.
As of right now, neither the GetFileVersionInfo nor VerQueryValue function are deprecated.
Example
This will extract the product version from kernel32.dll and print it to the console:
#pragma comment(lib, "version.lib")
static const wchar_t kernel32[] = L"\\kernel32.dll";
wchar_t *path = NULL;
void *ver = NULL, *block;
UINT n;
BOOL r;
DWORD versz, blocksz;
VS_FIXEDFILEINFO *vinfo;
path = malloc(sizeof(*path) * MAX_PATH);
if (!path)
abort();
n = GetSystemDirectory(path, MAX_PATH);
if (n >= MAX_PATH || n == 0 ||
n > MAX_PATH - sizeof(kernel32) / sizeof(*kernel32))
abort();
memcpy(path + n, kernel32, sizeof(kernel32));
versz = GetFileVersionInfoSize(path, NULL);
if (versz == 0)
abort();
ver = malloc(versz);
if (!ver)
abort();
r = GetFileVersionInfo(path, 0, versz, ver);
if (!r)
abort();
r = VerQueryValue(ver, L"\\", &block, &blocksz);
if (!r || blocksz < sizeof(VS_FIXEDFILEINFO))
abort();
vinfo = (VS_FIXEDFILEINFO *) block;
printf(
"Windows version: %d.%d.%d",
(int) HIWORD(vinfo->dwProductVersionMS),
(int) LOWORD(vinfo->dwProductVersionMS),
(int) HIWORD(vinfo->dwProductVersionLS));
free(path);
free(ver);
Yikes, the currently accepted answer is over-complicated. Here's how to get the version of the current windows (with build numbers) quickly and reliably without requiring manifests and other nonsense tricks. And works on Windows 2000 and newer (i.e. every version of Windows in existence).
Short answer: use RtlGetVersion.
Don't have the Windows Driver Development Kit? Then it's a little less simple than including the header and using the function. Here's how you do it both with and without the WDK.
With WDK, include:
// Required for RtlGetVersion()
#pragma comment(lib, "ntdll.lib")
#include <Ntddk.h>
Without WDK, include:
// Required for RtlGetVersion()
#pragma comment(lib, "ntdll.lib")
// Define the function because we don't have the driver development
// kit headers. We could probably acquire them but it makes development
// onboarding a pain in the ass for new employees.
extern "C" {
typedef LONG NTSTATUS, *PNTSTATUS;
#define STATUS_SUCCESS (0x00000000)
// Windows 2000 and newer
NTSYSAPI NTSTATUS NTAPI RtlGetVersion(PRTL_OSVERSIONINFOEXW lpVersionInformation);
}
Now, simply get the accurate version details:
RTL_OSVERSIONINFOEXW osVers;
osVers.dwOSVersionInfoSize = sizeof(osVers);
// fill the structure with version details
NTSTATUS status = RtlGetVersion(&osVers);
// this should always succeed
assert(status == STATUS_SUCCESS);
The osVers variable now contains the accurate major, minor, and build number. No need to read file versions and no need to dynamically load libraries at runtime.
Please vote this above the other answer so this correct code can be used in applications rather than the rube-goldberg other answer. Thanks.

Resources