Fixing Java error: jcuda.CudaException: CUDA_ERROR_INVALID_CONTEXT

If you try to use methods on a GPU with jCuda, you need to initialize a context:

cuInit(0);
cuDeviceGet(device, 0);
CUcontext context = new CUcontext();
cuCtxCreate(context, 0, device);
CUdevice device = new CUdevice();
cuDeviceGet(device, 0);

Note this gets the first GPU.

Once you’ve done this, you can then get information from the device:

long total[] = { 0L };
long free[] = { 0L };
cuMemGetInfo(total, free);