{"record":{"id":"4da809adbff430ba","repo":"java-native-access/jna","slug":"win32exception-from-native-getlasterror-after-4da809","errorCode":null,"errorMessage":"Win32Exception from native GetLastError after SetPriorityClass (background mode) failed","messagePattern":"Win32Exception from native GetLastError after SetPriorityClass \\(background mode\\) failed","errorType":"error_code","errorClass":"Win32Exception","httpStatus":null,"severity":"error","filePath":"contrib/platform/src/com/sun/jna/platform/win32/Kernel32Util.java","lineNumber":1300,"sourceCode":"        if (!isValidPriorityClass(dwPriorityClass)) {\n            throw new IllegalArgumentException(\"The given priority value is invalid!\");\n        }\n        if (!Kernel32.INSTANCE.SetPriorityClass(Kernel32.INSTANCE.GetCurrentProcess(), dwPriorityClass)) {\n            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());\n        }\n    }\n\n    /**\n     * Enables or disables \"background\" processing mode for the current process\n     *\n     * @param enable If true, enables \"background\" processing mode, otherwise disables it.\n     * @throws Win32Exception if an error occurs.\n     */\n    public static void setCurrentProcessBackgroundMode(final boolean enable) {\n        // Note: PROCESS_MODE_BACKGROUN_{BEGIN,END} only works with the \"current\" process handle!\n        final DWORD dwPriorityClass = enable ? Kernel32.PROCESS_MODE_BACKGROUND_BEGIN : Kernel32.PROCESS_MODE_BACKGROUND_END;\n        if (!Kernel32.INSTANCE.SetPriorityClass(Kernel32.INSTANCE.GetCurrentProcess(), dwPriorityClass)) {\n            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());\n        }\n    }\n\n    /**\n     * Gets the priority value of the current thread.\n     *\n     * @return The priority value of the current thread.\n     * @throws Win32Exception if an error occurs.\n     */\n    public static int getCurrentThreadPriority() {\n        final int nPriority = Kernel32.INSTANCE.GetThreadPriority(Kernel32.INSTANCE.GetCurrentThread());\n        if (!isValidThreadPriority(nPriority)) {\n            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());\n        }\n        return nPriority;\n    }\n\n    /**","sourceCodeStart":1282,"sourceCodeEnd":1318,"githubUrl":"https://github.com/java-native-access/jna/blob/d036ad9781adad4b66693e8fa7098e4ac665e0a3/contrib/platform/src/com/sun/jna/platform/win32/Kernel32Util.java#L1282-L1318","documentation":"setCurrentProcessBackgroundMode(boolean) maps 'enable' to PROCESS_MODE_BACKGROUND_BEGIN or PROCESS_MODE_BACKGROUND_END and calls SetPriorityClass on the current process. If the native call returns FALSE, the library throws a Win32Exception from GetLastError(). Background-begin mode requires elevated privileges and a process that is not a background process already; background-end fails when background mode was never started.","triggerScenarios":"Calling Kernel32Util.setCurrentProcessPriority-style background mode via Kernel32Util.setCurrentProcessBackgroundMode(true) without elevation, or calling setCurrentProcessBackgroundMode(false) when background mode was never enabled — both make SetPriorityClass fail with a native error.","commonSituations":"Non-admin processes attempting PROCESS_MODE_BACKGROUND_BEGIN (needs SeIncreaseBasePriorityPrivilege); unbalanced begin/end calls across code paths; Windows versions/job objects that reject the mode constants.","solutions":["Ensure every setCurrentProcessBackgroundMode(true) is paired with exactly one (false) call in a finally block.","Run elevated if enabling background mode, since BACKGROUND_BEGIN requires additional privilege.","Check Win32Exception.getErrorCode(): ERROR_PROCESS_MODE_ALREADY_BACKGROUND (402) means begin was called twice; ERROR_PROCESS_MODE_NOT_BACKGROUND (403) means end without begin.","Wrap in try-catch and fall back to normal priority classes if the mode switch fails."],"exampleFix":"// before\nKernel32Util.setCurrentProcessBackgroundMode(true);\n// after\nboolean bg = false;\ntry {\n    Kernel32Util.setCurrentProcessBackgroundMode(true);\n    bg = true;\n    // ... disk-heavy work ...\n} finally {\n    if (bg) Kernel32Util.setCurrentProcessBackgroundMode(false);\n}","handlingStrategy":"try-catch","validationCode":"// background begin requires elevation:\n// if (!isAdmin()) throw new IllegalStateException(\"background mode requires elevation\");\n// track state to avoid unbalanced calls:\nif (enable && backgroundModeActive) { throw new IllegalStateException(\"background mode already active\"); }\nif (!enable && !backgroundModeActive) { return; } // nothing to end","typeGuard":null,"tryCatchPattern":"try {\n    Kernel32Util.setCurrentProcessBackgroundMode(true);\n} catch (Win32Exception e) {\n    // 402 = already background, 403 = not background (for 'end')\n    log.warn(\"Background mode switch failed: {}\", e.getErrorCode());\n}","preventionTips":["Balance begin/end calls; put the 'end' call in a finally block.","Require elevation before enabling PROCESS_MODE_BACKGROUND_BEGIN.","Track mode state in a flag to avoid double-begin/end sequences.","Map error codes 402/403 (already/not background) to clear log messages."],"tags":["win32","jna","windows","background-mode","process-priority"],"backgroundTag":"permission-denied","analyzedSha":"d036ad9781adad4b66693e8fa7098e4ac665e0a3","analyzedAt":"2026-09-12T06:50:59.239Z","contentChangedAt":"2026-09-12T06:50:59.239Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}